Making Global Authorization Header in HttpClient Interceptor

1k views Asked by At

I am making a global authorization header in my app. I've used the interceptor so i won't declare the authorization header in my get() functions. Am i correctly implementing the interceptor since when i call the get() functions, it still asking for the token. It says token is not provided. Is there a problem in my auth.interceptor? Should i declare the authorization header bearer token in every get() functions? I thought the interceptor is called every time there's a request sent/receive?

auth.interceptor.ts

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    private authService: AuthService;

    constructor(private injector: Injector) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // Get the auth header from the service.
        this.authService = this.injector.get(AuthService);
        const token = this.authService.getToken();
            if (token) {
                req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
            }

            if (!req.headers.has('Content-Type')) {
                req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
            }

            req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
            return next.handle(req);
        }
}

products.component.ts

getAll() {
    return this.httpClient.get<any>(this.url).map(response => response.json());
    }
1

There are 1 answers

8
Aniruddha Das On BEST ANSWER

You are doing right way!

Interceptors are for intercepting all the http calls and you can change request which is global.

I think the problem in these conditions. you can debug them and resolve them.

            if (token) {
                req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
            }

            if (!req.headers.has('Content-Type')) {
                req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
            }

Maybe some they are returning null!

But if the timing is the issue to get the token, you can make async call to get the token.

this.authService.LoginUser().subscribe(( token) => { 
   if (token) { 
     req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) }); 
   } 

   if (!req.headers.has('Content-Type')) { 
     req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') }); 
   } 

   req = req.clone({ headers: req.headers.set('Accept', 'application/json') }); 
   return next.handle(req); 
} 
});