Rodgers Ouma
Rodgers Ouma

Reputation: 113

Angular6 angular-jwt not adding token to request headers

am using angular-jwt to intercept my requests and add the JWT token, but that doesn't seem to be happening.

This is my angular info:

Angular CLI: 6.0.8
Node: 9.11.2
OS: linux x64
Angular: 6.0.6
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.6.8
@angular-devkit/build-angular     0.6.8
@angular-devkit/build-optimizer   0.6.8
@angular-devkit/core              0.6.8
@angular-devkit/schematics        0.6.8
@angular/cli                      6.0.8
@ngtools/webpack                  6.0.8
@schematics/angular               0.6.8
@schematics/update                0.6.8
rxjs                              6.2.1
typescript                        2.7.2
webpack                           4.8.3

This is my app.module.ts:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    JwtModule.forRoot({
      config: {
        tokenGetter: tokenGetter,
        whitelistedDomains:['127.0.0.1:8000'],
        blacklistedRoutes: ['127.0.0.1:8000/api/v1/accounts/login/', '127.0.0.1:8000/api/v1/signup/'],
        authScheme: 'JWT ',
        throwNoTokenError: true
      }
    }),
    CommonModule,
}

This is a section of my package.json:

"@angular/router": "^6.0.3",
"@auth0/angular-jwt": "^2.0.0",

Sorry, I forgot to mention I have defined a tokenGetter function in app.module.ts:

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

Upvotes: 2

Views: 3118

Answers (3)

StepUp
StepUp

Reputation: 38094

The reason is not found of why authentication headers is not sent, however we can use HttpInterceptor to do this.

There is a great article about Angular Authentication: Using the Http Client and Http Interceptors.

We need to create an TokenInterceptor derived from HttpInterceptor class (I've created special folder Interceptors for that purpose):

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent,  
    HttpInterceptor} from '@angular/common/http';
import { AuthService } from '../services/auth.service';
import { Observable } from 'rxjs';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    constructor(public auth: AuthService) {}

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

and then it is necessary to add the above TokenInterceptor into app.module.ts:

@NgModule({
  declarations: [
    AppComponent        
  ],
  imports: [
    BrowserModule,   
    HttpClientModule,
    AppRoutingModule,
    CommonModule,
    FormsModule,
    ReactiveFormsModule,    
    RouterModule.forRoot([
      { path: '', component: TheComponent }            
    ]),
    JwtModule.forRoot({
      config: {
        tokenGetter: function tokenGetter() {
          console.log('tokenGetter called = ' + localStorage.getItem('authToken'));
          return localStorage.getItem('authToken');
        },
        whitelistedDomains: ['localhost:4200'],
        blacklistedRoutes: []
      }
    })
  ],
  providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: TokenInterceptor,
        multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

The code of AuthService:

export class AuthService extends AbstractRestService<any> {
    /* The other code is omitted for the brevity */
    get getToken() {
        return localStorage.getItem('authToken');
    }
}

Upvotes: 1

Chigozie Madubuko
Chigozie Madubuko

Reputation: 69

Now you just have to make request using Angular's HTTP Client

import { HttpClient } from '@angular/common/http';

export class AppComponent {
  constructor(public http: HttpClient) {}

  ping() {
    this.http
      .get('http://example.com/api/things')
      .subscribe(data => console.log(data), err => console.log(err));
  }
}

Source: https://github.com/auth0/angular2-jwt

Upvotes: 0

Ishant Gaurav
Ishant Gaurav

Reputation: 1203

Seems like you have not defined your tokenGetter funtion.

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

Upvotes: 1

Related Questions