Aleister Crowley
Aleister Crowley

Reputation: 721

Secure JWT token handling in React

I have been searching for a satisfying answer for an hour and I still can't figure out the answer to the question: how to securely store the JWT token on the client side with React?

From what I have read, the localStorage solution in undesirable as it's accessible from third-party scripts. A more secure solution proposed is to use a HttpOnly cookie, but the problem is, it is inaccessible via js, hence it is useless in React.

Therefore, how can I securely store a JWT token on the client side?

Upvotes: 9

Views: 1363

Answers (1)

Michal Trojanowski
Michal Trojanowski

Reputation: 12322

In short - you can't securely store token in the browser. If your code has access to the token, then any attacker can also get access to it. That said you can mitigate some risks and decide on a solution which might be "secure enough" for your needs.

E.g. it might be enough for you to keep tokens in the local storage, if losing such a token does not pose a great risk - maybe the data handled by your website is not sensitive.

A viable option is to keep the token in the memory. This way it's a bit more complicated to steal it. Then of course you need to get a new token every time you refresh the page, but you might use SSO cookies to automatically get new tokens in the background.

If you want to go with current security best practices for SPAs, you should investigate the Backend-For-Frontend pattern. You add a lightweight backend component which handles tokens and OAuth flows, and which uses regular cookie-based sessions in communication with your React app. At Curity we created an example implementation of such a component, which you could use as inspiration: https://github.com/curityio/bff-node-express

You can have a look at this great video: https://www.youtube.com/watch?v=lEnbi4KClVw where Philippe de Ryck goes into detail of why it's not possible to securely store tokens in SPAs.

Upvotes: 11

Related Questions