2

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

3 Answers 3

1

Seems like you have not defined your tokenGetter funtion.

export function tokenGetter() {
  return localStorage.getItem('access_token');
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

thanks working !
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.