Search code examples
angularjwtangular2-jwt

angular2-jwt missing authorization in header


I have an angular2 application which connects to an express/node server using jwt authentication.

I'm using angular2-jwt, and this is my configuration in app.module.ts

export function getAuthHttp(http) {
  return new AuthHttp(new AuthConfig({
    globalHeaders: [{'Accept': 'application/json'}],
    tokenName: 'my_token',
    tokenGetter: (() => localStorage.getItem('my_token')),
  }), http);
}

and then, for my http calls I use it like this

getQuestions(): Observable<any> {
  return this.authHttp
    .get(`${this.settings.api}/questions`)
    .map((response: Response) => response.json());
}

where this.settings.api is the authenticated url.

The thing is, this was working fine with my previous php server as it is. I just changed the url to use my new server in Node, and now the calls are failing because the token is not added to the headers.

When I check with chrome console the headers for the request I see this:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en,es-ES;q=0.8,es;q=0.6
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:3050
Origin:http://evil.com/
Pragma:no-cache
Referer:http://localhost:8100/
User-Agent:...

If I'm not wrong, there should be an Authorization: Bearer token in there, but it's missing.

I checked if the token can be retrieved when getting the AuthHttp and it's working, so the token exists and it's accessible.

Any ideas? Thanks,

EDIT I'm starting to think that this might be CORS related, as my old php server was in another machine, whereas the new node is in my own machine. Could that be it? How to fix it in that case?


Solution

  • So, in case anyone gets here, I solved this using a library for Express.

    https://www.npmjs.com/package/cors

    Easy to use, just added app.use(cors()); before any middleware in my Node server.