JwtModule doesn't add Authorization header

5.3k views Asked by At

On a Angular 7+ project, I tried to use the @auth0/angular-jwt module to add a Bearer token as Authorization header before sending request to a protected rest api.

I sent a request on the whitelisted URL and got a 401 exception, then I checked the Network (using fiddler) which header was transmited, the Authorization header was not there.

I followed all of the readme indication, and even checked If I included only once the HttpClientModule.

app.module.ts :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { JwtModule } from '@auth0/angular-jwt';
import { tokenGetter } from './environment';

import { AppComponent } from './app.component';
// ... other components

@NgModule({
  declarations: [
    AppComponent
    // ... other components
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule,
    JwtModule.forRoot({
      config: {
        tokenGetter: tokenGetter,
        whitelistedDomains: ["localhost:8080"]
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

environment.ts :

export function tokenGetter() {
    return localStorage.getItem('access_token');
}
1

There are 1 answers

1
techjunkie On

I am on Angular 9 and this code snippet worked for JwtModule in the app.module.ts file. It's no longer whitelistedomains and blacklisteddomains anymore it's allowedDomains and disallowedRoutes in the latest version now. Hope this helps the official doc is here https://github.com/auth0/angular2-jwt

    JwtModule.forRoot({
  config: {
    tokenGetter: () => {
      return localStorage.getItem('token');
    },
    allowedDomains: ['localhost:5000'],
    disallowedRoutes: ['localhost:5000/api/auth']
  }
})

]

You can also do export function as well for the tokenGetter, but I just wanted to show how it would work in one code snippet. Happy coding!

package.json:

    "@auth0/angular-jwt": "^5.0.1",

app.module.ts import code:

import { HttpClientModule } from '@angular/common/http';
import { JwtModule } from '@auth0/angular-jwt';

Complete imports code:

  imports: [
BrowserModule,
HttpClientModule,
FormsModule,
BrowserAnimationsModule,
BsDropdownModule.forRoot(),
NgxGalleryModule,
TabsModule.forRoot(),
RouterModule.forRoot(appRoutes),
JwtModule.forRoot({
  config: {
    tokenGetter: () => {
      return localStorage.getItem('token');
    },
    allowedDomains: ['localhost:5000'],
    disallowedRoutes: ['localhost:5000/api/auth']
  }
})

],

techjunkieblog