Home > other >  Where to store JWT token in react / client side in secure way?
Where to store JWT token in react / client side in secure way?

Time:09-24

We are developing a web application in react js and using Odoo as a backend.

My web app will be hosted at abc.com and the backend is at xyz.com.

Now, when I call login API at my backend It is giving a JWT token in response. Now my question is where we should store this JWT token for subsequent use.

I found few similar questions but I am not sure where They should be stored in my use case. Can anyone please suggest to me where we should store it on the client-side?

Thanks a lot in advance!

CodePudding user response:

You have a few options where you can store the token. Each option has it's flaws, and which one should you choose depends on your concrete needs and use cases. It's also good to know that there is no secure way to store tokens in the browser.

  1. Storing in memory. You can keep the token in a variable in the script's memory. It will be hard to steal the token with an XSS attack, but you will need a new token every time the user refreshes the page.

  2. Storing in local storage. This gives you the possibility to reuse the token when the user refreshes the page. With this option, however, it's much easier for an XSS attack to steal your tokens.

  3. Storing in a httponly, secure, same-site cookie. This is currently considered as the most secure option for SPAs, but in this scenario you will not be able to set the Authorization header straight from the SPA, you can only rely on the browser to add the secure cookie to your request. This means, that you might need some additional backend components, which will extract tokens from cookies (and maybe put them in those cookies, in the first place). This is usually referred to as a Token Handler component, or a Backend-for-Frontend. If this is the level of security that you need you can have a look at an example implementation of such a BFF, that we did at Curity: https://curity.io/resources/learn/back-end-for-front-end/

Have a look also at this great video by Philippe de Ryck about security of tokens in the browser: https://pragmaticwebsecurity.com/talks/xssoauth.html

CodePudding user response:

You can store the obtained token in a cookie. If you are using the axios library for your request, you can set the token to be handled in the interceptors of axios

export function getToken() {
  for (const i in TokenKey) {
    if (Cookies.get(TokenKey[i])) return Cookies.get(TokenKey[i])
  }

service.interceptors.request.use(
  config => {
    const token = getToken() || store.getters.token
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }

)

  • Related