What I want:

  • Store a JWT in localStorage. The JWT contains claims about authorization.
  • Prevent the JWT from being stolen and used by an attacker (using XSS)
  • Avoid CSRF

Storing the JWT in localStorage is bad since exploiting XSS would lead to a stolen JWT, which an attacker could use for authorization.

Storing JWT in http only cookie is bad since it doesn't have enough space for the claims.

A possible solution is to:

  • Create a http only cookie with a sessionId
  • Store JWT in localStorage with the same sessionId encrypted inside
  • On the server, verify that the sessionId in the JWT and the cookie matches before using the claims.

This way the JWT can be stolen, but cannot be used unless the attacker also has the sessionId from the cookie. Also, CSRF is not possible since a cookie is not enough for authorization.

Are there any flaws with my reasoning? Are there any easier ways to accomplish the same thing?

1 Answer 1


A http-only cookie is strong given that clientside JS cannot read it. Your solution seems pretty sound. Only recommendation I would make is to use a client side framework that offers XSS protection, like ReactJS. Or sanitize all HTML string inputs. You could also add a short expiration time length to your JWTs. Sorry, I would make this a comment but don't have enough rep.

  • If I've encrypted my JWT with JOSE standard, does that mean I can store it in localStorage (without the question-asker's session ID method). Commented Feb 19, 2023 at 15:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .