'Where to store token from auth header in React

I am currently working on a medium scale app and am a month into learning React. I got to the part where I need to authenticate users. I have written some code and It is working, but I don't know is it secure enough. When my users login, they are assigned with a JWT token like this:

await axios.post(APIbase + '/login', {
          username: username, password: password
       }).then(res=>{
           const token = res.data.token;
           localStorage.setItem('token', token);
       }).catch(err => {
           console.log(err);
        });

And then, when the user makes a request to a server it send the token by an auth header like this:

 const token = localStorage.getItem('token');
      const headers = { Authorization: `Bearer ${token}`};
      const detailResult= await axios.get(API.base + API.details, {
      headers:headers});

Is this safe enough? I heard that this is a not really a good practice, but I am not sure what exactly should I do.



Solution 1:[1]

Local storage is generally used for this kind of token, but keep in mind any JS on the page can access local storage. If you have any 3rd party code, it can get to the token by simply reading the local storage.

If you want a bit more secure way of storing it, you can use HTTPonly, secure cookie. That way it will not be accessible by JS and it will also be sent automatically in any request to the API, but it requires changes on the server to implement cookies instead of Authorization header.

You can also use a BFF (backend for frontend) approach with a server handling session then you don't need to store the token on the client side either (and only store in on BFF linked to the session), but keep using it for requests to the API from the BFF.

Security is a complex field and has a lot of trade-offs. There is no one correct answer for every use case.

This does really belong to react domain but is a more beta question and there is a special stack exchange for this: https://security.stackexchange.com/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jakub Kotrs