strangeQuirks
strangeQuirks

Reputation: 5920

React authentication using localStorage

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?

Upvotes: 0

Views: 2738

Answers (1)

JulienD
JulienD

Reputation: 7293

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.

Upvotes: 1

Related Questions