Fabio
Fabio

Reputation: 15

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]
})

Upvotes: 1

Views: 2752

Answers (3)

ReMadWeb
ReMadWeb

Reputation: 58

I am a bit late. There are docs on that keycloak-angular Github repository. Here is an example how to include BearerTokenInterceptor, which adds Bearer Access Token to your http request to your api: https://github.com/mauriciovigolo/keycloak-angular/blob/main/docs/interceptors.md

Upvotes: 0

andymel
andymel

Reputation: 5686

In my case the HttpClient was not used to do the requests.

Instead fetch has been used directly and that is not intercepted by angular.

So if you have the HttpInterceptor in place and it does not work, be sure HttpClient is used to do the requests.

I changed fetch(...) to http.get(...) and it worked

Upvotes: 1

Zets
Zets

Reputation: 26

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);
}

Upvotes: 1

Related Questions