3

Hello I am wondering is it a good practice to keep the token in the local storage in react js because I read this article https://dev.to/rdegges/please-stop-using-local-storage-1i04 and there they say it is not good to use local storage for sensitive data. Also I am coding a API with a security and session for first time and I will be glad if someone explain me how things must be done right - if there are some resources to read etc. And if it is OK to use token with local storage how this must be done ? how is it saved I saw there are questions asked for saving into (ls) but i can't done this in my request only before that or after that should I use a state variable ? Thanks in advance for any help.

onSubmit = e => {

    e.preventDefault();
    fetch(  `/myresource/customer/${this.state.query}/${this.state.password}`)
        .then(res => res.json())
        .then((result) => {
                console.log(result);
                this.setState({
                    user: result,
                    password: result
                    localStorage.setItem('token', '');  <-- Here is not legal to set the token value where should it be saved.
                }
            );
         }
     )

     this.setState( { welcomeMsg: 'Hello, ' } );
}
Banana
  • 2,435
  • 7
  • 34
  • 60
  • 1
    store it in localStorage – Kunal Mukherjee May 09 '19 at 13:35
  • 1
    You can't do `localStorage.setItem('token', '');` inside `this.setState`. Your code will get errors – Vencovsky May 09 '19 at 13:36
  • @KunalMukherjee where to set the value from the state to the storage or ? i can't pass directly into the request. –  May 09 '19 at 13:37
  • @Vencovsky i made a comment in the code that i have asked how to be done this is the second part of my question –  May 09 '19 at 13:37
  • @AvinashMahlawat if the user reloads the page, it will get lost, right? Doesn't make sense to logout or lose all the data only if you reload the page – Vencovsky May 09 '19 at 13:39

1 Answers1

6

A JWT needs to be stored in a safe place inside the user's browser.

If you store it inside localStorage, it's accessible by any script inside your page (which is as bad as it sounds as an XSS attack can let an external attacker get access to the token).

Don't store it in local storage (or session storage). If any of the 3rd part scripts you include in your page gets compromised, it can access all your users' tokens.

The JWT needs to be stored inside an HttpOnly cookie, a special kind of cookie that's only sent in HTTP requests to the server, and it's never accessible (both for reading or writing) from JavaScript running in the browser.

from: https://logrocket.com/blog/jwt-authentication-best-practices/

So you will need to set the cookie in the server side for it to be safe.

You can find an already widely accepted answer to this question here: https://stackoverflow.com/a/44209185/11465265

Fardenz
  • 103
  • 5