Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve a Bearer Token from an Authorization Header in JavaScript (Angular 2/4)?

Tags:

In JavaScript I have a method which authenticates to my server via an http post request successfully.

The response data from my server is sending a JWT in an Authorization header like so:

Authorization: Bearer mytoken12345abc

I can retrieve the authorization header successfully from my servers response data like so for example:

let authheader = response.headers.get('Authorization');

But how do I parse this? Is "Bearer" a key? so something like:

let token = authheader.Bearer 

which obviously is not correct. What can I try next?

In other words, is the following the best approach?

let token = response.headers.get('Authorization');
let parsedToken = token.slice(7);
like image 888
DevMike Avatar asked Jun 12 '17 10:06

DevMike


1 Answers

According to the jwt.io docu,

Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema.

Therefore using the JWT in the Authorization header is supposed to be used by the client, not the server for the initial response.

The correct way is to get the token as part of the response body. We use a

 { jwt: TOKEN } 

type scheme for that. Then you can easily access it via your response.json().

You can access the header value directly using response.headers.get(...) but then you will have to split, substr or regex-match to get the actual token.

like image 151
TommyF Avatar answered Sep 30 '22 00:09

TommyF