Difference Between Localstorage, Sessionstorage, Session and Cookies

What is the difference between localStorage, sessionStorage, session and cookies?

This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.

In all cases, these storage mechanisms will be specific to an individual browser on an individual computer/device. Any requirement to store data on an ongoing basis across sessions will need to involve your application server side - most likely using a database, but possibly XML or a text/CSV file.

localStorage, sessionStorage, and cookies are all client storage solutions. Session data is held on the server where it remains under your direct control.

localStorage and sessionStorage

localStorage and sessionStorage are relatively new APIs (meaning, not all legacy browsers will support them) and are near identical (both in APIs and capabilities) with the sole exception of persistence. sessionStorage (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network).

Clearly, if the data you are storing needs to be available on an ongoing basis then localStorage is preferable to sessionStorage - although you should note both can be cleared by the user so you should not rely on the continuing existence of data in either case.

localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications.

Cookies

This is also true for cookies, these can be trivially tampered with by the user, and data can also be read from them in plain text - so if you are wanting to store sensitive data then the session is really your only option. If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.

On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.

As cookies are used for authentication purposes and persistence of user data, all cookies valid for a page are sent from the browser to the server for every request to the same domain - this includes the original page request, any subsequent Ajax requests, all images, stylesheets, scripts, and fonts. For this reason, cookies should not be used to store large amounts of information. The browser may also impose limits on the size of information that can be stored in cookies. Typically cookies are used to store identifying tokens for authentication, session, and advertising tracking. The tokens are typically not human readable information in and of themselves, but encrypted identifiers linked to your application or database.

localStorage vs. sessionStorage vs. Cookies

In terms of capabilities, cookies, sessionStorage, and localStorage only allow you to store strings - it is possible to implicitly convert primitive values when setting (these will need to be converted back to use them as their type after reading) but not Objects or Arrays (it is possible to JSON serialise them to store them using the APIs). Session storage will generally allow you to store any primitives or objects supported by your Server Side language/framework.

Client-side vs. Server-side

As HTTP is a stateless protocol - web applications have no way of identifying a user from previous visits on returning to the web site - session data usually relies on a cookie token to identify the user for repeat visits (although rarely URL parameters may be used for the same purpose). Data will usually have a sliding expiry time (renewed each time the user visits), and depending on your server/framework data will either be stored in-process (meaning data will be lost if the web server crashes or is restarted) or externally in a state server or database. This is also necessary when using a web-farm (more than one server for a given website).

As session data is completely controlled by your application (server side) it is the best place for anything sensitive or secure in nature.

The obvious disadvantage of server-side data is scalability - server resources are required for each user for the duration of the session, and that any data needed client side must be sent with each request. As the server has no way of knowing if a user navigates to another site or closes their browser, session data must expire after a given time to avoid all server resources being taken up by abandoned sessions. When using session data you should, therefore, be aware of the possibility that data will have expired and been lost, especially on pages with long forms. It will also be lost if the user deletes their cookies or switches browsers/devices.

Some web frameworks/developers use hidden HTML inputs to persist data from one page of a form to another to avoid session expiration.

localStorage, sessionStorage, and cookies are all subject to "same-origin" rules which means browsers should prevent access to the data except the domain that set the information to start with.

For further reading on client storage technologies see Dive Into Html 5.

localStorage vs sessionStorage vs cookies

localStorage and sessionStorage are both so-called WebStorages and features of HTML5.

localStorage stores information as long as the user does not delete them.

sessionStorage stores information as long as the session goes. Usually until the user closes the tab/browser.

cookies are simply cookies, which are supported by older browsers and usually are a fallback for frameworks that use the above mentioned WebStorages.

In contrast cookies can store way less information then WebStorages and the information in WebStorages is never transferred to the server.

Keep in mind that the EU has a regulation that requires websites to inform their users about the usage of cookies. I dont know whether this also applies to WebStorages

Local Storage vs Cookies

Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?

If it's your client (your JavaScript), then by all means switch. You're wasting bandwidth by sending all the data in each HTTP header.

If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.

You'll want to leave your session cookie as a cookie either way though.

As per the technical difference, and also my understanding:

  1. Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it's per cookie. Local Storage is as big as 5MB per domainSO Question also mentions it.

  2. localStorage is an implementation of the Storage Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.

HTML5 Local storage vs. Session storage

localStorage and sessionStorage both extend Storage. There is no difference between them except for the intended "non-persistence" of sessionStorage.

That is, the data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

For sessionStorage, changes are only available per tab. Changes made are saved and available for the current page in that tab until it is closed. Once it is closed, the stored data is deleted.

Difference between Session Storage, Local Storage and Cookies in AngularJS

1) It is correct that sessionStorage is temporary, and it has been designed to do so.

2) Local storage will solve the issue of the login going away with a new browser session being opened or after waiting a long time, but no, localStorage will not act as a session cookie for browser requests.

3) Many different server side applications support encryption and tamper-resistant cookie support for applications. That being said, it is always best not to store user passwords in the client, maybe a token perhaps that your server will recognize and be able to decrypt/decode and look up the correct user record.

4) I would say nowadays yes, cookies are generally accepted to be safe, however that is always a possibility, and depending on your clients or audience you may have an issue there. Also sessions won't work if cookies are disabled in the browser. (Though my outlook on this is speculation on a general population, ie: don't quote me on that)

My recommendation for your needs is to set a session variable when the user encounters the page. Then store the result in localStorage or with a cookie, and then when the user returns to the application after the session has died, have some architecture set up to re-authenticate and re-assign the session automatically.

Hope this helps!

Edit: Session Cookies are shared between browser tabs within the same window. However Session Storage has been pointed out not to be.

Do I have to store tokens in cookies or localstorage or session?

This answer is based on the stateless approach and therefore it doesn't talk about the traditional session management

You have asked two altogether different questions:

  1. Shopping cart - which is more related to business functionality
  2. OAuth 2 & JWT - which is related to security and authentication

As an user of an ecommerce website, I'd expect that any item I add to my shopping cart from my mobile device while commuting to my workplace, should be available in the cart when I login to the website from my PC after reaching home. Therefore, the cart data should be saved in the back-end DB and linked to my user account.

When it comes to authentication using OAuth 2.0, the JWT access token and / or refresh token need to be stored somewhere in the client device, so that once the user authenticates himself by providing login credentials, he doesn't need to provide his credentials again to navigate through the website. In this context, the browser local storage, session storage and cookies are all valid options. However, note that here the cookie is not linked to any session on the server side. In other words, the cookie doesn't store any session id. The cookie is merely used as a storage for access token which is passed to the server with every http request and the server then validates the token using the digital signature to ensure that it is not tampered and it is not expired.

Although all three storage options for access and / or refresh tokens are popular, cookie seems to be the most secured option when used in the correct way.

To understand this better, I recommend you read this and this along with the OAuth 2.0 specification.

Update On 16-Feb-2019

I said earlier that cookie seems to be the most secured options. I'd like to further clarify the point here.

The reason I think browser localStorage and sessionStorage do not provide enough security for storing auth tokens are as follows:

  1. If XSS occurs, the malicious script can easily read the tokens from there and send them to a remote server. There on-wards the remote server or attacker would have no problem in impersonating the victim user.

  2. localStorage and sessionStorage are not shared across sub-domains. So, if we have two SPA running on different sub-domains, we won't get the SSO functionality because the token stored by one app won't be available to the other app within the organization. There are some solutions using iframe, but those look more like workarounds rather than a good solution. And when the response header X-Frame-Options is used to avoid clickjacking attacks with iframe, any solution with iframe is out of question.

These risks can, however, be mitigated by using a fingerprint (as mentioned in OWASP JWT Cheat Sheet) which again in turn requires a cookie.

The idea of fingerprint is, generate a cryptographically strong random string of bytes. The Base64 string of the raw string will then be stored in a HttpOnly, Secure, SameSite cookie with name prefix __Secure-. Proper values for Domain and Path attributes should be used as per business requirement. A SHA256 hash of the string will also be passed in a claim of JWT. Thus even if an XSS attack sends the JWT access token to an attacker controlled remote server, it cannot send the original string in cookie and as a result the server can reject the request based on the absence of the cookie. The cookie being HttpOnly cannot be read by XSS scripts.

Therefore, even when we use localStorage and sessionStorage, we have to use a cookie to make it secured. On top of that, we add the sub-domain restriction as mentioned above.

Now, the only concern about using a cookie to store JWT is, CSRF attack. Since we use SameSite cookie, CSRF is mitigated because cross-site requests (AJAX or just through hyperlinks) are not possible. If the site is used in any old browser or some other not so popular browsers that do not support SameSite cookie, we can still mitigate CSRF by additionally using a CSRF cookie with a cryptographically strong random value such that every AJAX request reads the cookie value and add the cookie value in a custom HTTP header (except GET and HEAD requests which are not supposed to do any state modifications). Since CSRF cannot read anything due to same origin policy and it is based on exploiting the unsafe HTTP methods like POST, PUT and DELETE, this CSRF cookie will mitigate the CSRF risk. This approach of using CSRF cookie is used by all modern SPA frameworks. The Angular approach is mentioned here.

Also, since the cookie is httpOnly and Secured, XSS script cannot read it. Thus XSS is also mitigated.

It may be also worth mentioning that XSS and script injection can be further mitigated by using appropriate content-security-policy response header.

Other CSRF mitigation approaches

  1. State Variable (Auth0 uses it) - The client will generate and pass with every request a cryptographically strong random nonce which the server will echo back along with its response allowing the client to validate the nonce. It's explained in Auth0 doc.
  2. Always check the referer header and accept requests only when referer is a trusted domain. If referer header is absent or a non-whitelisted domain, simply reject the request. When using SSL/TLS referrer is usually present. Landing pages (that is mostly informational and not containing login form or any secured content) may be little relaxed ​and allow requests with missing referer header.
  3. TRACE HTTP method should be blocked in the server as this can be used to read the httpOnly cookie.
  4. Also, set the header Strict-Transport-Security: max-age=; includeSubDomains​ to allow only secured connections to prevent any man-in-the-middle overwrite the CSRF cookies from a sub-domain.

Difference between Session Cookies and General Cookies?

This is an implementation detail of the website, so this can't be directly answered.

The session cookie may be created server side and associated with the saved session, but it still has to be saved client side so that the client browser can remind the server which session to use (and verify it).

From the browser's perspective, there is no difference between a session cookie and any other cookie. It's just a cookie. So there's no technical reason why all the cookies can't coexist as long as there are no name collisions.

From the web server's perspective, if the non-session cookies had a purpose, that purpose is likely still there when there is a session, so deleting them to use the session in its place would probably just make the code more complex. But this doesn't say if they will or won't do that.

So, another way to ask the question would be "Are the authors of the website going to be lazy and not bother deleting redundant cookies, or are they going to be fancy and merge them into the session and clean things up?"

Also consider the session cookie and the other cookies may all have different lifetimes, so it might not make sense to merge them anyway.

Difference between sessionStorage and express-session?

The main difference is:

sessionStorage stores data (client-side) inside browser.

express-session stores data to (server-side) and it also stores sessionID into the browser as cookie.


express-session:
For each visit to a page, the cookie is sent along with the sessionID and the backend code can then fetch the session data. So the user has access to his own session data.
The data in the server side session is private. Only the server can see it. The cookie is deleted when the browser is closed (our session data is also automatically deleted by the server depending on our setting.)

SessionStorage: is a local database in the browser that you can access via client-side JavaScript. Basically it’s a key/value store. This database is not private. You, or anyone using your browser, can see the contents using the developer tools of the browser. The “session” in sessionStorage means that all data is deleted when the browser is closed.

Whats the difference between web cookies and Local storage?

There're some rather inaccurate statements in your question. Re:1 - redux doesn't persist data forever in browser. This is actually what localStorage, cookies and local DB does.

But with that correction in mind, it's a good question.

  1. redux state is the most "reactive" one. It's aim is to let components within your app to have access to the "single source of truth". It stores data directly in JS, in memory. It can be quickly accessed and updated by your components, without any medium (like local storage), that's why it's handy for it's purposes.

  2. local storage indeed is capable in storing data in your browser forever. However, reading from it and writing to it takes extra time and burden in order to keep data sync, because you can't interact with it synchronously, it's not the best choice for using as primary data source for your component. But it's good to hydrating some data on app inits (for example, you can store the JWT token there, and then hydrate it into the redux store in app load - it's a common pattern)

  3. Cookies is not a good place to store the info in broad sense. It's rather a placeholder for storing some session-specific identifiers for communicating them to your backend. Check out this one for more info: https://medium.com/datadriveninvestor/cookies-vs-local-storage-2f3732c7d977#:~:text=Differences%20between%20cookies%20and%20localStorage&text=Cookies%20are%20mainly%20for%20reading,you%20more%20to%20work%20with.



Related Topics



Leave a reply



Submit