I am trying to figure out how to build a basic login/signup feature for my React application. So I am considering creating a HoC/parent class that does things such as logging in and checking if a user logged in. SO now I have come to you to figure out the best way to store whether a user is logged in or not. What I saw is using localStorage. But that could be accessed by anyone really right so I can just store a flag saying isLoggedIn or something? Would I have to encrypt some token such as a username.password and then on every page load do a call to the DB? That seems a little much. Or have a missunderstood something?
1 Answers
You can use JSON Web Tokens (JWT).
When the user logs in, call say /login of your backend to check the password against your database. If successful, issue a JWT containing the username and its role, for instance (not the password).
You can always tell then if the user is logged in by verifying directly with Javascript the cryptographic signature of the token (if the readable content, such as the user name, has been altered, then the signature will not match anymore). This way you don't need to interrogate the database until the token expires.
What I saw is using localStorage. But that could be accessed by anyone really right
No. It also has the advantage over cookies that it is accessible only from the same domain. In principle there is a way that your token gets stolen (e.g. XSS attacks, or copied from dev tools on your laptop when you are away), but the expiration time that you will add to it will make it valid for only a few hours.

- 7,102
- 9
- 50
- 84
-
though in the browser console, cant I do something like localStorage.getItem() on a victims computer and then on my computer set the value? – strangeQuirks Oct 10 '17 at 11:13
-
1@user1009698 Yes, you can, and use it until it expires. Same thing with a cookie though, this is not the localStorage's fault: instead of `localStorage.getItem(.)`, just do `document.cookie`. Lock you screen when you are away! – JulienD Oct 10 '17 at 11:17
-
@JulienD It is not completely true because cookies with `HttpOnly` flag are not accessible from javascript. – Nergal Sep 04 '19 at 08:11