3
votes

I need to store JWT token which is generated when a valid user login after proper registration through REST API. I read and find these ways to store JWT in client site: local storage, session storage, cookies, HttpOnly cookie, Browser memory (React state).

Need suggestion to store JWT in the proper method and also can access some certain APIs for get with JWT token as post request header parameter user-related data.

here is my login code part where I store JWT token to window object at this point, saved previously on local storage but now need to store safely in other ways except local storage or cookies.

const handleSubmitLogin = evt => {
evt.preventDefault();
var cart = new Cart();

var request = new NFRequest();
var response = request.api(HTTP_METHOD.POST, '/auth', {
    'email_address': allValuesLogin.email_login,
    'password': allValuesLogin.password_login,
    'cart_list': cart.getCartPostData(),
});
response.then((res) => {
    if (res.type === 'success') {
        window.$token = res.data.token
        setLoginSuccess('Successfully Login')
        setTimeout(()=> {
            setLoginSuccess('');
        }, 3000)
        cart.handle({ action_type: "RESET_ITEMS" });
        Router.push('/account')
    } else {
        setLoginError('Wrong Email or Password')
        setTimeout(()=> {
            setLoginError('');
        }, 3000);
    }
});
}

here I store the JWT token:window.$token = res.data.token

Thank you.

3

3 Answers

3
votes

It's up to you on how to store it. Generally, this is the most to least secure:

  1. Browser memory
  2. Http-only cookie
  3. local storage
  4. session storage / cookie

The most important thing is to make sure your website is protected against XSS and CSRF attacks.

0
votes

Storing JWT tokens within localStorage or session storage is suggested of course with this in production a proper SSL certificate should be used to help prevent this like a man in the middle attack.

Also there are different advantages to local/session

sessionStorage is removed after browser is closed however localStorage is shared between tabs. This is handy for sharing state between tabs. However you ned to manage removing the JWT token.

0
votes

Update: It's not a good idea to store JWT tokens in local storage.

Read this article => https://www.rdegges.com/2018/please-stop-using-local-storage/


set the token with localStorage

    if (res.type === 'success')
        localStorage.setItem('token', res.data.token);
        setLoginSuccess('Successfully Login')
        setTimeout(()=> {
            setLoginSuccess('');
        }, 3000)
        cart.handle({ action_type: "RESET_ITEMS" });
        Router.push('/account')
    } 

to remove the token you use: localStorage.removeItem('token');