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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With