0

I am developing a web with React, Redux and React-Cookie. In this web i have a login system, in which I send a POST request to my Backend API that will send me back the user's data I need for my components (including it's token for the cookie), and I need this data to be Persistent. Currently I am storing the user data in my store, and the boolean of isAuthenticated in the local storage of the client (which I don't know how insecure is this procedure). Where should I store this data? maybe in a cookie? Also if you have some advice regarding the way i store the authenticated boolean would be really nice as well.

Fran M
  • 229
  • 1
  • 4
  • 12

1 Answers1

4

The common practice is to store the user object in the local storage and have another key for the token (or you can embed the token inside the user object).

There is no need for authenticated boolean, you should check if the user exists in the local storage and if it does then your user is authenticated.

in your logout function make sure to delete the user key from your local storage so the above check will return false.

function isAuthenticated() {
 return !!localstorage.getItem('user');
}

function login(credentials) {
  fetch(....)
  .then(res => res.json())
  .then(({user, token}) => {
    localstorage.setItem('user', {...user, token});
   })
}

function logout() {
  localstorage.removeItem('user');
}
AfikDeri
  • 2,069
  • 17
  • 19
  • Is not insecure to store data (like email, or user_id, or admin boolean, etc...) in the local storage? I've been looking into and it seems that js files can access the local storage. – Fran M Nov 04 '19 at 11:06
  • It all depends on your app, if the user id is sensitive information then don't store it there. If you want to check if the user is admin you can perform an ajax call to the backend with the token and get his permissions back. for every change you make in the backend you must validate the token. storing the logged in user data in the localstorage is not a security issue, since the user that you store is the same user that logged in and knows his credentials anyway. – AfikDeri Nov 04 '19 at 11:25