JWT Express API not seeing HTTPInterceptor auth header

Issue

I have the following implementation of JWT Middleware in ExpressJS

const authenticateJWT = (req, res, next) => {
  const authHeader = req.headers.authorization;
  ...    
};

and this HTTPInterceptor implementation in Angular:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        request = request.clone({
            setHeaders: { Authorization: 'Bearer ...' }
        });

        return next.handle(request);
    }

if I console.log the request variable in the interceptor I can see that the authorization header is successfully added but then in the JWT middleware it’s undefined.
What could be the reason?

Solution

You can use this code in your interceptor:

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let headers = request.headers;
        headers = headers.append("Authorization", 'Bearer ...');
        
        request = request.clone({
            headers: headers
        });

        return next.handle(request);
    }
    

Answered By – Souhail HARRATI

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published