4
votes

I have tried to pass JWT token in the header. I am using the below code. I have injected the auth service nad imported necessary files. But it's not working.

I want to add JWT to the HTTP header for every request? How can I achieve this? I need every request to be authenticated with an authorization token by my backend.

Angular app module code:

providers: [
   AuthGuard,
   { 
       provide: HTTP_INTERCEPTORS, 
       useClass: TokenInterceptor, 
       multi: true 
   }
]

Angular interceptor code:

import { Inject, Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { switchMap } from 'rxjs/operators';
import { NbAuthJWTToken, NbAuthService, NB_AUTH_TOKEN_INTERCEPTOR_FILTER ,NbAuthToken} from '@nebular/auth';

/**
 * TokenInterceptor
 * @see https://angular.io/guide/http#intercepting-all-requests-or-responses
 */

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    private tokenService: NbAuthJWTToken;

    constructor(private injector: Injector,
        @Inject(NB_AUTH_TOKEN_INTERCEPTOR_FILTER) protected filter) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        debugger;
        if (!this.filter(req)) {
          return this.authService.isAuthenticatedOrRefresh()
            .pipe(
              switchMap(authenticated => {
                if (authenticated) {
                    debugger;
                    return this.authService.getToken().pipe(
                      switchMap((token: NbAuthToken) => {
                        const JWT = `Bearer ${token.getValue()}`;
                        req = req.clone({
                          setHeaders: {
                            Authorization: JWT,
                          },
                        });
                        return next.handle(req);
                      }),
                    )
                } else {
                    // Request is sent to server without authentication so that the client code
                    // receives the 401/403 error and can act as desired ('session expired', redirect to login, aso)
                  return next.handle(req);
                }
              }),
            )
        } else {
      return next.handle(req);
    }
  }

  protected get authService(): NbAuthService {
    return this.injector.get(NbAuthService);
  }

}

What I am doing wrong?

3
What is not working? Were are you getting your errors? What is happening, and what is expected behaviour? - John
I am not getting any error. I want to add a JWT to the HTTP header for every request? How can I achieve this? I need every request to be authenticated with an authorization token by my backend. - Sudhakar SJ
A token is not passing in the header. But when I console the token in any component It's printing. - Sudhakar SJ
Did you tried to debug it? I guess some conditions are no right for you. - NicuVlad
A good idea would be to add also the content of the "authService" - NicuVlad

3 Answers

0
votes

You need to debug your code in order to check why the token is not added. But you can simplify the logic:

  intercept(req, next) {
    const tokenizedReq = req.clone({
      setHeaders: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });

    return next.handle(tokenizedReq);
  } 

This way you try to add the token for each request. If token is missing the user will get a 401 for the request. When the user authenticates just add the token to the local storage.

0
votes

Try doing this:

req = req.clone({ headers: req.headers.set('Authorization', JWT) });

Also make sure to step through the code and see what happens at that point. Ensure you are storing the token when it was first generated, and retrieving it from storage for subsequent calls (I believe you are already doing this, but just in case you aren't).

0
votes

you probably forgot to add the interceptor in providers array in app module

  providers: [
{provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true}]