Angular 5 HttpInterceptor and sending Authorization Token in header

Vincent Nguyen picture Vincent Nguyen · Apr 18, 2018 · Viewed 8.4k times · Source

My flow is login page -> home page.

Login page has no token, after logging in, server provides token and user is redirected to home page.

Home page sends the token to server, token is verified, server sends back data to display on front end.

Problem:

HttpInterceptor firing on login request Cannot read property 'token' of null. I would like to have the interceptor somehow ignore the login api request and only intercept on subsequent calls if token exists.

Answer

Fateh Mohamed picture Fateh Mohamed · Apr 18, 2018

hello you can a key value in your header to distinguish login from other requests, and create an interceptor to check if that key exist to delete the token

import { HttpClient, HttpHeaders } from '@angular/common/http';
...
login(username, password) {
    let headers = new HttpHeaders();
    headers = headers.append('noToken', 'noToken');
    return this.http.post(loginUrl, data, {headers: headers})
    ...
}

then create your interceptor

export class TokenInterceptor implements HttpInterceptor {
constructor() {}

intercept(httpReq: HttpRequest<any>, next: HttpHandler): 
 Observable<HttpEvent<any>> {
 let headers = httpReq.headers
  .set('Content-Type', 'application/json');

 if (headers.get('noToken') === 'noToken') {
   headers = headers.delete('Authorization').delete('noToken');
 }

 const newReq = httpReq.clone({headers: headers});

 return next.handle(newReq);
 }
}

and add it to your app module providers

import { TokenInterceptor } from './token.interceptor';

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

Working Solution

auth.interceptor.ts

export class AuthInterceptor implements HttpInterceptor {
    constructor(public auth: HouseaccountsService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if(req.headers.get('notoken') !== 'noToken') {
            req = req.clone({
                setHeaders: {
                    Authorization: JSON.parse(localStorage.getItem('currentUser')).token
                }
            });
        }

        return next.handle(req);
    }
}

service.ts

login(user) {
        let loginHeaders = {
            headers: new HttpHeaders({
                'Content-Type': 'application/json',
                'noToken': 'noToken'
            })
        }
        return this.http.post<any>(this.url + '/login', JSON.stringify(user), loginHeaders);
    }