htmlauthenticationauthorizationlocal-storagesession-storage

How to combine advantages of localStorage and sessionStorage


I want to share my authentication token between browser tabs which would suggest to use HTML5 localStorage. But I don't want anything related to authentication to stay in my storage when the browser is closed which would suggest using HTML5 sessionStorage.

Reference 1 related to this topic (click):

That means that you can't share between tabs, for this you should use localStorage

Reference 2 related to this topic (click):

Therefore, it's recommended not to store any sensitive information in local storage

How can I combine the sharing of my authentication token between tabs and still make sure that when the browser closes nothing stays behind in storage?

How do other websites solve this seemingly simple problem.


Solution

  • We use cookies.

    Storages have their uses. But cookies meet all your requirements.

    Sometime the best solution is the simplest solution. No need to reinvent the wheel.

    Cookie Security

    Session cookie is stored on disk like sessionStorage (in case the browser crash and need to recover). So they are about equally secure in term of local disk read/write.

    Both cookie and storage processing script may be acquired or even stolen during http transfer, so you must use HTTPS for both cases. (This is the least you should do.)

    Cookie can be configured to be HTTP only, preventing JavaScript from accessing it, thus making immune from XSS script and greasemonkey hijacking.

    In case when an auth token is stolen, we also associate each token with the machine's user agent and ip. This prevent the token from being used by someone from external network. If you want, you can add more content negotiation headers to the mix - not all robots copy all headers.

    For another level of security, you can add client side fingerprinting. These fingerprints must be captured on client side and transferred over network, so they are not bulletproof, but they will force internal attackers (attackers on same network with the user) to jump through another hoop.

    At this point, they will usually switch to easier attacks outside your control.