ReactJS and DRF: How to store JWT token inside HTTPonly cookies?

Currently, I have the login functionality working on my web app, after I make a login request the server responds with a JSON object that contains 2 tokens:

This is the login function:

async function login() {
    const data = {
            "email": "[email protected]",
            "password": "testPassword123"
        }
    const response = await Backend.post('auth/login/', data)
    console.log(response.data)
}

And this is the response:

{
"access": "access_token_here",
"refresh": "refresh_token_here" 
}

According to Postman, this response also contains 3 cookies:

1) access_token=access_token_here; Path=/; Domain=localhost; HttpOnly; Expires=Thu, 29 Oct 2020 06:49:56 GMT;
2) csrftoken=csrf_token_here; Path=/; Domain=localhost; Expires=Thu, 28 Oct 2021 06:44:56 GMT;
3) sessionid=session_id_here; Path=/; Domain=localhost; HttpOnly; Expires=Thu, 12 Nov 2020 06:44:56 GMT;

To make a request to a protected endpoint in the server, I can send the access_token as a cookie or as a Bearer token. My understanding is that storing these tokens in Local Storage is not very secure.

So how can I store them in httpOnly cookie? Or is there a better way of dealing with this?

My backend server is using Django Rest Framework.


Solution 1:

I guess that you would like to set httpOnly cookie because it will be more secure than setting token (tokens) in localStorage?

The most secure way is to store token only in memory (state) and do not store it in cookies or localStorage. After every page refresh, force the user to login again. This is how bank's websites are working.

If you need to store the token on the client-side (you don't want to force login after every refresh) then I would recommend localStorage instead of cookies. React itself is protected against XSS. But if there will be XSS then, of course, localStorage data is easy to read but also data in cookies (even httpOnly) can be exploited (by sending requests with available cookies). Both localStorage and cookies are vulnerable to XSS, but as I wrote React has protection against XSS. Using localStorage is also easier in implementation.

Please see this discussion: link to reacjs subreddit.