RasMason
RasMason

Reputation: 2212

No Authorization header found when being sent via Angular 4 interceptor - Node.js

I'm building an app with login.

The user can login and a token is returned to the front end.

The problem is occurring when, I'm sending the token back to the server to be verified.

I'm using a HttpInterceptor to send the Authorization header to the server.

When I log in the console:

  console.log(cloned.headers.get("Authorization"))

The header is displayed fine, however, when logged in the express middleware

console.log(req.headers.authorization);

I get undefined

Also below are the request headers from the network tab, as you can see, no Authorization

enter image description here

Interceptor:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const id_token = localStorage.getItem("id_token");

    if (id_token) {
      const cloned = req.clone({
        headers: req.headers.set("Authorization", "Bearer " + id_token)
      });
      // console.log(cloned)
      console.log(cloned.headers.get("Authorization"))
      return next.handle(cloned);
    }
    else {
      return next.handle(req);
    }
  }
}

express:

router.use('/edit', function(req, res, next) {
  console.log(req.headers.authorization);
  const checkIfAuthenticated = expressJwt({
    secret: RSA_PUBLIC_KEY
  });

  if (checkIfAuthenticated) {
    return res.status(401).json({
      title: 'Not Authorised',
      error: 'You are not authorised'
    });
  }
})

Upvotes: 0

Views: 7719

Answers (3)

Raines
Raines

Reputation: 111

Have the same problem with angular 5 and laravel 5 backend with tymon/jwt laravel package to handle token authentication.

The problem in my case is from backend. In my api route I use: Route::any(...)

When I changed the any to the right http verb (get, post...) The problem go away: Route::get(...)

When I inspect the network panel in chrome, the request to backend was sent twice, first one with no token and the other with token

Upvotes: 1

Lucas
Lucas

Reputation: 10303

Here are some comments on how to implement interceptors that might help your case:

1) Interceptors require angular version 4.3 || >

2) Remember to provide the interceptor in our main app.module:

/** Interceptors */
import {HttpClientModule, HTTP_INTERCEPTORS} from '@angular/common/http'; <-- notice the common in @angular/common/http 
import {TokenInterceptor} from './path/to/TokenInterceptor ';

@NgModule({
  imports: [
    ...
    HttpClientModule
  ],
  providers: [
    {provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

3) In your service that reaches the endpoint, make sure to add the new http client:

import {HttpClient} from '@angular/common/http'; <-- Super important to include new HttpClient from @angular/common/http instead of old http from @angular/http...

@Injectable()
export class MyService {

    constructor(private http: HttpClient ) { }
// your GET POST and other requests made with http will now have the desired header...

4) Also, edit your interceptor code and add setHeaders :

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const id_token = localStorage.getItem("id_token");

    if (id_token) {
       req = req.clone({
          setHeaders: {
             Authorization: `Bearer ${id_token}`
          }
       });
       return next.handle(req);
    }

If you already did follow this steps but your header doesnt appear, paste your service and module code

Upvotes: 0

dave0688
dave0688

Reputation: 5770

The Authorization-header is hidden by default. In your backend you need to expose the header:

Access-Control-Expose-Headers: Authorization

Please see this thread as a reference:

Angular 2: Get Authorization header

@Update: Sorry, misunderstood your question. Please recheck your second console.log(). You're logging:

console.log(req.headers.authorization);

Shouldn't that be

console.log(req.headers.get("Authorization"));

instead?

Upvotes: 1

Related Questions