0

I am searching for a safe way to keep the user logged in in my Progressive Web Application.

When the user installs the PWA he needs to authenticate by the traditional auth method (e-mail and password). But on the client-side I will also generate a long random key and save that in localStorage. That key will be sent to the server and saved as hash in the database.

Then when the user opens the app, the app checks if a key exists in the localStorage. If it does, the key gets authenticated against the hashed version in the database. If it matches the user gets automatically logged in.

To facilitate this I will also save the user ID in localStorage.

I will put a time-to-live of a month on the localStorage so the user has to re-authenticate sometimes.

Is this safe?

O'Niel
  • 2,914
  • 3
  • 20
  • 31
  • When the app calls some service, how will your server know who is sending this request? – mentallurg Apr 21 '23 at 19:06
  • 1
    why use localStorage instead of a secure, http-only cookie with a token or hash for remembering the user and/or persisting the session? – browsermator Apr 21 '23 at 19:43
  • (slightly more secure) strategy for storing long-term secrets locally: https://security.stackexchange.com/a/244506/228961 – brynk Apr 21 '23 at 21:48
  • The other problem (not security related) is that localStorage gets cleared by iOS after 7 days of inactivity. That's ITP https://webkit.org/tracking-prevention/ – charlax Feb 16 '24 at 18:43

1 Answers1

4

This is significantly less secure than properly implemented cookie-based authentication.

  • It's highly vulnerable to cross-site scripting attacks, as the OWASP points out. Any XSS vulnerability anywhere on the site potentially gives the attacker unrestricted access to localStorage. With cookies, you can prevent this using the httpOnly attribute.
  • Third-party scripts loaded into your site (JavaScript libraries etc.) also have unrestricted access to localStorage.
  • The extremely long duration for which the token will be valid makes it likely that the user loses control over the token. For example, they may already have cleared their browser data and forgotten the token, but the server still considers the token valid until either the month is over or the user logs in and overrides the previous tokens (depending on your implementation). The same would be true for long-lived cookies, of course.
  • The fact that localStorage is an unusual place to store tokens is a problem by itself, because users may not be aware that there's sensitive data in localStorage. For example, when trying to clear all sensitive browser data, they may only delete the cookies and leave localStorage intact.
Ja1024
  • 5,769
  • 14
  • 21