1

Here's my scenario:

When a user logs in, an API call is made and if his credentials are valid, a token is returned. I need to store the authentication state (to keep the user logged in) and the token somewhere. The token will be used to make other API calls.

I've read these posts: 1, 2, 3 (and some others) which all seem to contradict each other; whether it's localStorage, cookies or JWT, all are being deemed as unsafe by different people. I have also read about react-redux too but I'm not sure about it.

For now I am completely lost on which solution best suits my needs since I am new to reactJs. So, what is the proper way to go on about this?

Jolan
  • 681
  • 12
  • 39
  • Redux is orthogonal; it's just a state management tool. The "proper" way depends; "a token" is somewhat vague. API calls to who? *Your* app? External apps? – Dave Newton Jun 09 '20 at 16:19
  • @DaveNewton each user is assigned a token. This token will be used for the API calls to the backend which will fetch data to be displayed on the different pages of the react app – Jolan Jun 09 '20 at 16:24
  • Simple answer use `cookies`. `JWT`'s isn't supposed to be used to store tokens and `localStorage` isn't safe. I'm struggling with implementing cookies on reactjs as well. – Tony Jun 16 '20 at 14:09
  • @Tony yes, i finally used `cookies`. I used `js-cookie` (https://github.com/js-cookie/js-cookie). If you are having trouble, check it out; it is really simple to use – Jolan Jun 16 '20 at 15:36
  • 1
    @jo12345678 finally something that works. Thanks a bunch. – Tony Jun 16 '20 at 16:44

1 Answers1

1

The most common practice is storing your token in cookie and set HttpOnly to true, so that any javascript code cannot read your token programmatically.

I suppose you are using axios as ajax client, you can make a request like this

axios.get('https://example.com/api', {
  withCredentials: true
})

by doing this, axios will send your cookies to remote server automatically

Wenhan Wu
  • 96
  • 2