Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store access-token in react.js?

I am building an app in Reactjs. I have to make fetch call, after verifying the access_token. On signup, access_token are acquired from back-end server. But, where to store these access_token. Is there any way of making these access_token global, so that all component can access it. I have used local storage, cache and session storage, but those are not advisable. Held up in this issue for past few days, any solutions for it. Thnks in advance.

like image 807
Thananjaya S Avatar asked Feb 26 '18 07:02

Thananjaya S


People also ask

Where should I store token react?

Storing JWT Token We need to store this token somewhere. We can store it as a client-side cookie or in a localStorage or sessionStorage. There are pros and cons in each option but for this app, we'll store it in sessionStorage.

Where do you store access token?

Tokens received from OAuth providers are stored in a Client Access Token Store. You can configure client access token stores under the Libraries > OAuth2 Stores node in the Policy Studio tree view.

How do you store a token in session storage in react JS?

Go to localhost:3000 or whatever port you are running it on, and go to a non-member register here and let's register for another account. Make sure it has an e-mail that you haven't used yet. It can be whatever, and hit create account. We get back the token and user object restoring the users.

Where should I store JWT token react?

Have your server save the JWT token as an HttpOnly cookie. The browser will handle the rest. If you are in a situation where your front end is making CORS requests for the token, you will need to set the withcredentials flag for AJAX requests.


2 Answers

Available options and limitations:

There are 2 types of options for storing your token:

  1. Web Storage API: which offers 2 mechanisms: sessionStorage and localStorage. Data stored here will always be available to your Javascript code and cannot be accessed from the backend. Thus you will have to manually add it to your requests in a header for example. This storage is only available to your app's domain and not to sub domains. The main difference between these 2 mechanisms is in data expiry:
  • sessionStorage: Data available only for a session (until the browser or tab is closed).
  • localStorage: Stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser cache/Locally Stored Data
  1. Cookies: Automatically sent to your backend with the subsequent requests. Expiry and visibility to your Javascript code can be controlled. Can be available to your app's sub domains.

You have to consider 2 aspects when designing your authentication mechanism:

  • Security: An access or identity token is a sensitive information. The main types of attacks to always consider are Cross Site Scripting (XSS) and Cross Site Request Forgery (CSRF).
  • Functional requirements: Should the user stay logged in when the browser is closed? How long will be his session? etc

For security concerns, OWASP does not recommend storing sensitive data in a Web Storage. You can check their CheatSheetSeries page. You can also read this detailed article for more details.

The reason is mainly linked to the XSS vulnerability. If your frontend is not a 100% protected against XSS attacks then a malicious code can get executed in your web page and it would have access to the token. It is very difficult to be fully XSS-proof as it can be caused by one of the Javascript librairies you use.

Cookies on the other hand can be unaccessible to Javascript if they are set as HttpOnly. Now the problem with cookies is that they can easily make your website vulnerable to CSRF. SameSite cookies can mitigate that type of attacks. However, older versions of browsers don't support that type of cookies so other methods are available such as the use of a state variable. It is detailed in this Auth0 documentation article.

Suggested solution:

To safely store your token, I would recommend that you use a combination of 2 cookies as described below:

A JWT token has the following structure: header.payload.signature

In general a useful information is present in the payload such as the user roles (that can be used to adapt/hide parts of the UI). So it's important to keep that part available to the Javascript code.

Once the authentication flow finished and JWT token created in the backend, the idea is to:

  1. Store the header.payload part in a SameSite Secure Cookie (so available only through https and still availble to the JS code)
  2. Store the signature part in a SameSite Secure HttpOnly Cookie
  3. Implement a middleware in your backend to resconstruct the JWT token from those 2 cookies and put it in the header: Authorization: Bearer your_token

You can set an expiry for the cookies to meet your app's requirements.

This idea was suggested and very well described in this article by Peter Locke.

like image 149
Anouar Avatar answered Sep 17 '22 13:09

Anouar


Although late to the party, I feel like sharing my thoughts on this topic. Anouar gave a good answer, including the http-only cookies that are considered save against XSS, pointed out the CSRF vulnerability and linked the article by Peter Locke.

However, in my case, I need the application to be 100% stateless, meaning I cannot use cookies.

From a security point of view, storing the access token in a persistent location (like localStorage, window,..) is bad practice. So you could use either redux (or react.js built in state/context) to store the JWT in a variable. This would protect the token from the mentioned attacks, but null it once the page is refreshed.

What I do to solve this is using a refresh token, that I store in localStorage (you may use session storage or similar if you like). The single purpose of that refresh token is to obtain a new access token, and the backend makes sure that the refresh token is not stolen (e.g. implement a counter that gets checked against). I keep the access token in cache (a variable in my app), and once expired or lost due to a reload, i use the refresh token to obtain a new access token.

Obviously this only works if you also build the backend (or at least if the backend implements refresh tokens). If you deal with an existing API that does not implement refresh token or alike, and saving the access token in a variable is not an option for you (due to null on reload), you could also encrypt the token with an application secret before you save it to localStorage (or sessions storage, or...yea you get the idea). Note, that decrypting the token takes some time and can slow down your app. You may therefor save the encrypted token to localStorage (or...) and decrypt it only once after a refresh to then keep it in a state/redux variable until you refresh again/decrypt it from localStorage again etc.

A last word on this topic: Auth is critical infrastructure to an app, and although there is an obvious difference between a fun game and an online bank (you might want to be "paranoid" about that bank, while only "concerned" about the game), answers like "localStorage is totally fine" or "what could happen in the worst case? expire after 1hour" are dangerous and simply wrong. Machines can do alot of damage in a few seconds, and you do not want to leave that gap open. If you are too lazy to secure your app, maybe you want to use an existing solution instead of building your own.

That said, JWT / token auth is fairly new to the game (a few years, but not as mature as other topics in dev). It takes some time and effort to find a working solution, but let us keep building secure software instead of flooding the web with quick hacks.

Best, & happy coding.

like image 30
randmin Avatar answered Sep 16 '22 13:09

randmin