angularangular2-jwt

Set Jwt Token in Local Storage - Angular


I'm using auth0/angular-jwt library on branch v1.0 which supports HttpInterceptor.

Here is my app.module.ts:

  imports: [
    BrowserModule,
    HttpClientModule,
    HttpModule,
    JwtModule.forRoot({
      config: {
        authScheme: 'Bearer',
        headerName: 'Authorization',
        tokenGetter: () => {
          return localStorage.getItem('access_token');
        },
      }
    }),


I return from my backend side:
{
    "access_token": "token - I removed it for the example)",
    "expires_in": "2017-12-25T07:26:30Z",
    "id": "19a6609f-4ed9-4804-adad-a83ss670c7ba"
}

The problem is that the token isn't saved in localStorage. Have I missed something?


Solution

  • Once you've got the token from the HTTP \ backend service you need to write it to local storage like below, where result equals the response in JSON from the server.

    localStorage.setItem ('token', result.token);

    I just covered this in a course yesterday The Complete Angular Course it's worth looking at, it covers authorization and authentication. It's a really good course and will help no end.