Aman Dwivedi
Aman Dwivedi

Reputation: 174

How to store JWT in browser?

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

Answers (4)

Jayakrishnan
Jayakrishnan

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

human
human

Reputation: 2441

Building on Chris's answer:

  1. JWTs should never be stored in your localStorage
  2. In fact, they shouldn't even be stored in your cookies, unless you are able to implement very strict CSRF protection

Checkout this for motivation

  • JWT as an id_token is like your user credentials
  • JWT as an access_token is like your session token

The most secure option is in-memory. Checkout this for a deep dive

Upvotes: 0

Chris
Chris

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

Rogue45
Rogue45

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

Related Questions