Angular 4 custom http interceptor. localStorage.getItem() returns null

1.7k Views Asked by At

I am using Azure B2C authentication. Upon successful redirect, the access token gets stored in browser's localStorage and for subsequent API calls, following http interceptor class is supposed to attach the auth token to all outbound requests. Issue is that localStorage.getItem() returns null when trying to read auth token from localStorage. Here is the code,

import { HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } 
from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HttpManagerInterceptor implements HttpInterceptor {

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
    req = req.clone({ headers: req.headers.set('X-CRSP-TOKEN', 'ToBeImplemented') });

    // this line always returns null
    const authToken = window.localStorage.getItem('auth_token');

    console.log('Inside http interceptor. Access token: ' + authToken);
    if (authToken) {
        req = req.clone({ headers: req.headers.set('Authorization', `Bearer 
        ${authToken}`) });
    }

    console.log(JSON.stringify(req.headers));
    return next.handle(req);
 }

Console logs

Token found:  
  eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ilg1ZVhrNHh5b2pORnVtMWtsMll0djhkbE5QNC1jNTdkTzZRR1RWQndhTmsifQ.eyJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vYmY5Njg3YWYtOTliMy00YzU3LWI2YjAtOWE5OGIzNTRhOWQyL3YyLjAvIiwiZXhwIjoxNTA0MTMxNzM3LCJuYmYiOjE1MDQxMjgxMzcsImF1ZCI6IjI4ZGM0NjZkLWRhZGUtNDNkMy04ZjBhLTJkYmNlNTQxYmIxMyIsIm9pZCI6IjcyMzljZWVjLTMzN2ItNDlmNS04YzViLTVkMzcwZGEwZmIxOCIsImdpdmVuX25hbWUiOiJaZWVzaGFuIiwiZmFtaWx5X25hbWUiOiJIYWlkZXIiLCJzdWIiOiJOb3Qgc3VwcG9ydGVkIGN1cnJlbnRseS4gVXNlIG9pZCBjbGFpbS4iLCJlbWFpbHMiOlsiWmVlc2hhbi5IYWlkZXJAY3JzcC5jaGljYWdvYm9vdGguZWR1Il0sImF6cCI6IjI4ZGM0NjZkLWRhZGUtNDNkMy04ZjBhLTJkYmNlNTQxYmIxMyIsInZlciI6IjEuMCJ9.DUebFoHuzLXIbjMOmRrCRYswMB1g-7J6kVOaYyI3-b5AuaTjrcTtTsZkiGbloseaKqKtKoRtO72EkyQ2XvJ2lyhCBybpD4skeOcwQ2p_RBcO1dlFSoWIOkQK7WPN_f3tLxzuvKgrcPuR2LurB_n0uEq8PTdMIKXgfuCVDUSjxGrcwlzGi61k2g24wzO-u9YdN5Xqx0eFqooE0hhiifTsAsXPNJhXTmLinr4qt25bRfvVs1UpYNk6hv1RQ3afrg7UZavr-Osjh5amQ6Qi_q6kKTQWorB9Cgoj_UTIA8ojkK-6y7D8uzY-YtLzomuNvD8mELCeZC8ZdPbbibzC2Kj6Rw

Inside http interceptor. Access token: null

I am suspecting if INTERCEPTORS initialized or created before localStorage is available to use. If that is the case and there is no workaround, can anyone suggest other solutions?

Your help will be appreciated!

1

There are 1 best solutions below

1
On BEST ANSWER

Inject window inside your component

@Inject(WINDOW) private window: any