fullstackopen-2019 / fullstackopen-2019.github.io

Other
349 stars 357 forks source link

[Security] Do not store auth token in localStorage #654

Closed mirorauhala closed 4 years ago

mirorauhala commented 4 years ago

It is not safe to store sensitive data in localStorage. LocalStorage is readable by JavaScript, which in this case has been its intended purpose. However that's not how you do a secure authentication system.

Consider the following:

How to overcome this? Use cookies. Especially httpOnly cookies with the secure flag. They've been battle-tested for decades now. The httpOnly flag tells the browser to never give JavaScript access to the cookie value. The secure flag tells the browser to never send the cookie to an unencrypted site.

"But this wont work since we're using React, right?" Wrong. You can still serve your users a SPA site with a login page. The login page will make an XHR request to the backend API endpoint with the username and password as POST parameters. The server will respond with the user data if successful and with an error message if not.

That's it. That's how easy it is.

"Wait what happens if I reload the page?" Well the page will reload but you are still logged in. How? Well the magic is in the session cookie. The server sent you the user data on the body, but the header information contained the cookie which your SPA JavaScript never saw. The client browser just grabbed the cookie automatically and stores it. It also sends it back to the server an all further requests. If the session dies or is not set, the backend will respond with an error asking for authentication and the client can display it in a nice, meaningful way.

Additionally, the cookie most likely has to have SameSite flag set to Lax for this to work. One could also host the SPA page from static file host such as GitHub Pages or Amazon S3 but have the backend endpoint on a subdomain and on a separate server somewhere else. For that to be secure some CORS headers would be necessary.

[1] https://www.theregister.co.uk/2018/11/26/npm_repo_bitcoin_stealer/

Kaltsoon commented 4 years ago

You make really good points and I agree with you, HTTP only cookies would be a much safer choice. However, we have to understand that the focus of this course is not making a bulletproof authentication mechanism.

I think we should mention the dangers of storing sensitive data (such as access tokens in our case) in local storage but making bigger changes to the material would not be worth the effort.