Reputation: 174
I'm using JSON Web Tokens (JWT) for the first time. I'm making a Node.js app using Hydra-Express framework. I want to use JWT for authentication. As per the docs, I'm returning the JSON token to the front-end.
var tokenData = {
username: req.body.username,
};
var result = {
username: req.body.username,
token: jwt.sign(tokenData, 'secret', { expiresIn: 60 * 60 })
};
res.json(result);
But I don't know how to save this JSON token to my browser header so that it doesn't get lost and is again sent to the back-end along with the header. How to save it in my browser storage and add it to the request header each time a request is sent to the backend?
Upvotes: 1
Views: 4232
Reputation: 4294
You can use HTML5 web storage or cookie to store your JWT token and read from it whenever you want to send your request to web API.
This link will help you decide the best match for your app.
Hope it helps!!
Upvotes: 0
Reputation: 2441
Building on Chris's answer:
The most secure option is in-memory. Checkout this for a deep dive
Upvotes: 0
Reputation: 14218
Security advice:
Trying to keep it short: cookies(http-only & secure flag) are vulnerable to CSRF but not XSS. JWT in localstorage is vulnerable to XSS but not CSRF
The best you can do is to minimize the risk: store the JWT in a cookie store a csrf_token in localstorage
To make it stateless: Include the csrf_token in the JWT payload and check serverside if the JWT csrf_token and the csrf_token read from localstorage and provided in the header match.
This requires an attacker to get the csrf_token through XSS (e.g. you use a compromised 3rd party js library in your site or do not apply sanitation) And then he needs to trigger a csrf request with the csrf_token (e.g. embedded img src tag or form in a webpage /email)
This combination makes it a lot harder for an attacker (but not impossible).
It provides the same security level as a normal session based authentication with csrf_tokens, but does not require state.
Upvotes: 5
Reputation: 381
When it comes back store you entire token in sessionStorage
sessionStorage.token = json.access_token;
To access the payload split the jwt token into its header.payload.signature parts and grab just the payload
var enc = json.access_token.split(".")[1];
Then parse the base64
var payload = JSON.parse(window.atob(enc));
Then you can grab and use your verified payload data payload.sub, payload.role ...etc
Upvotes: 1