angulartypescriptkeycloak

Angular-Keycloak is not adding the bearer token by default to my http requests


I'm trying to implement keycloak-angular but I'm not able to add the bearer token by default to my http requests.

"keycloak-angular": "9.1.0" "keycloak-js": "16.0.0" "Angular": "13.0.2"

    function initializeKeycloak(keycloak: KeycloakService) {
  return async () =>
   await keycloak.init({
      config: {
        url: 'https://127.0.0.1:8443/auth',
        realm: '*****',
        clientId: '****',
      },
      initOptions: {
        onLoad: 'login-required',
        checkLoginIframe: false,
      },
      loadUserProfileAtStartUp: true,
      enableBearerInterceptor: true,
      bearerExcludedUrls: [],
      bearerPrefix:'Bearer '
    });
}



 @NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    CoreModule,
    BrowserModule,
    KeycloakAngularModule,
    AppRoutingModule
  ],
  providers: [
    { provide: LOCALE_ID, useValue: 'it' },
    {
      provide: APP_INITIALIZER,
      useFactory: initializeKeycloak, 
      multi: true,
      deps: [KeycloakService]
    },
  ],
  bootstrap: [AppComponent]
})

Solution

  • You have to use an HttpInterceptor to add custom headers at each api call. Create your interceptor, and add it to AppModule

    providers: [
     {
       provide: HTTP_INTERCEPTORS,
       useClass: ApiInterceptor,
       multi: true,
     }
    ],
    

    Implement the intercept function :

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer #YOUR_TOKEN_HERE#`
        }
      });
    
      return next.handle(request);
    }