Angular2-jwt: Issues with whitelist when build with AOT

Created on 4 Oct 2017  路  3Comments  路  Source: auth0/angular2-jwt

I am creating an application using;

    "@angular/core": "^4.4.4",
    "@angular/cli": "^1.4.4",
    "@auth0/angular-jwt": "^1.0.0-beta.9",

Importing @auth0/angular-jwt in the following way;

export function getAccessToken(): string {
    return localStorage.getItem('auth_token');
}

export const jwtConfig = {
    tokenGetter: getAccessToken,
    whitelistedDomains: ['localhost:8081']
}

@NgModule({
    declarations: [
        AppComponent,
        LoginComponent
    ],
    imports: [
        ....
        JwtModule.forRoot({
            config: jwtConfig
        })
    ]
}

This works correctly when running with ng serve, however when running AOT with ng serve --aot (or ng build --prod) it fails to validate the domain against the whilelist.

It looks as though the whitelistDomains[] is empty when it comes to check in isWhitelistedDomain. I'm struggling to debug this but I think the JwtInterceptor constructor is called without the provided config.

Not sure if I'm doing something wrong, or this is a bug. Any ideas?

Most helpful comment

@wannabegeek
try this method

export function getJwtToken(): string {
    return localStorage.getItem('token');
}
JwtModule.forRoot({
        config: {
            headerName: 'Authorization',
            tokenGetter: getJwtToken,
            authScheme: 'Bearer ',
            whitelistedDomains: ['localhost:4200'],
        },
    }),

All 3 comments

I have a workaround for this by using an options factory. e.g.

export function jwtOptionsFactory(tokenService) {
    return {
        tokenGetter: () => localStorage.getItem('auth_token'),
        whitelistedDomains: ['localhost:8081']
      }
}

@NgModule({
    declarations: [
        AppComponent,
        LoginComponent
    ],
    imports: [
        ....
        jwtOptionsProvider: {
            provide: JWT_OPTIONS,
            useFactory: jwtOptionsFactory
        }
    ]
}

However, I don't understand why the original way doesn't work!

@wannabegeek
try this method

export function getJwtToken(): string {
    return localStorage.getItem('token');
}
JwtModule.forRoot({
        config: {
            headerName: 'Authorization',
            tokenGetter: getJwtToken,
            authScheme: 'Bearer ',
            whitelistedDomains: ['localhost:4200'],
        },
    }),

using jwtOptionsFactory worked for me, but had to add deps option

jwtOptionsProvider: {
    provide: JWT_OPTIONS,
    useFactory: jwtOptionsFactory,
    deps:[]
}
Was this page helpful?
0 / 5 - 0 ratings