Setting multiply cookies [duplicate] - javascript

I want to reduce load times on my websites by moving all cookies into local storage since they seem to have the same functionality. Are there any pros/cons (especially performance-wise) in using local storage to replace cookie functionality except for the obvious compatibility issues?

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:
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 10MB per domain — this Stack Overflow question also mentions it.
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.

In the context of JWTs, Stormpath have written a fairly helpful article outlining possible ways to store them, and the (dis-)advantages pertaining to each method.
It also has a short overview of XSS and CSRF attacks, and how you can combat them.
I've attached some short snippets of the article below, in case their article is taken offline/their site goes down.
Local Storage
Problems:
Web Storage (localStorage/sessionStorage) is accessible through JavaScript on the same domain. This means that any JavaScript running on your site will have access to web storage, and because of this can be vulnerable to cross-site scripting (XSS) attacks. XSS in a nutshell is a type of vulnerability where an attacker can inject JavaScript that will run on your page. Basic XSS attacks attempt to inject JavaScript through form inputs, where the attacker puts alert('You are Hacked'); into a form to see if it is run by the browser and can be viewed by other users.
Prevention:
To prevent XSS, the common response is to escape and encode all untrusted data. But this is far from the full story. In 2015, modern web apps use JavaScript hosted on CDNs or outside infrastructure. Modern web apps include 3rd party JavaScript libraries for A/B testing, funnel/market analysis, and ads. We use package managers like Bower to import other peoples’ code into our apps.
What if only one of the scripts you use is compromised? Malicious
JavaScript can be embedded on the page, and Web Storage is
compromised. These types of XSS attacks can get everyone’s Web Storage
that visits your site, without their knowledge. This is probably why a
bunch of organizations advise not to store anything of value or trust
any information in web storage. This includes session identifiers and
tokens.
As a storage mechanism, Web Storage does not enforce any secure
standards during transfer. Whoever reads Web Storage and uses it must
do their due diligence to ensure they always send the JWT over HTTPS
and never HTTP.
Cookies
Problems:
Cookies, when used with the HttpOnly cookie flag, are not accessible through JavaScript, and are immune to XSS. You can also set the Secure cookie flag to guarantee the cookie is only sent over HTTPS. This is one of the main reasons that cookies have been leveraged in the past to store tokens or session data. Modern developers are hesitant to use cookies because they traditionally required state to be stored on the server, thus breaking RESTful best practices. Cookies as a storage mechanism do not require state to be stored on the server if you are storing a JWT in the cookie. This is because the JWT encapsulates everything the server needs to serve the request.
However, cookies are vulnerable to a different type of attack:
cross-site request forgery (CSRF). A CSRF attack is a type of attack
that occurs when a malicious web site, email, or blog causes a user’s
web browser to perform an unwanted action on a trusted site on which
the user is currently authenticated. This is an exploit of how the
browser handles cookies. A cookie can only be sent to the domains in
which it is allowed. By default, this is the domain that originally
set the cookie. The cookie will be sent for a request regardless of
whether you are on galaxies.com or hahagonnahackyou.com.
Prevention:
Modern browsers support the SameSite flag, in addition to HttpOnly and Secure. The purpose of this flag is to prevent the cookie from being transmitted in cross-site requests, preventing many kinds of CSRF attack.
For browsers that do not support SameSite, CSRF can be prevented by using synchronized token patterns. This
sounds complicated, but all modern web frameworks have support for
this.
For example, AngularJS has a solution to validate that the cookie is
accessible by only your domain. Straight from AngularJS docs:
When performing XHR requests, the $http service reads a token from a
cookie (by default, XSRF-TOKEN) and sets it as an HTTP header
(X-XSRF-TOKEN). Since only JavaScript that runs on your domain can
read the cookie, your server can be assured that the XHR came from
JavaScript running on your domain. You can make this CSRF protection
stateless by including a xsrfToken JWT claim:
{
"iss": "http://galaxies.com",
"exp": 1300819380,
"scopes": ["explorer", "solar-harvester", "seller"],
"sub": "tom#andromeda.com",
"xsrfToken": "d9b9714c-7ac0-42e0-8696-2dae95dbc33e"
}
Leveraging your web app framework’s CSRF protection makes cookies rock
solid for storing a JWT. CSRF can also be partially prevented by
checking the HTTP Referer and Origin header from your API. CSRF
attacks will have Referer and Origin headers that are unrelated to
your application.
The full article can be found here:
https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage/
They also have a helpful article on how to best design and implement JWTs, with regards to the structure of the token itself:
https://stormpath.com/blog/jwt-the-right-way/

With localStorage, web applications can store data locally within the user's browser. Before HTML5, application data had to be stored in cookies, included in every server request. Large amounts of data can be stored locally, without affecting website performance. Although localStorage is more modern, there are some pros and cons to both techniques.
Cookies
Pros
Legacy support (it's been around forever)
Persistent data
Expiration dates
Cookies can be marked as HTTPOnly which might limit XSS atacks to user browser during his sesion (does not guarantee full immunity to XSS atacks).
Cons
Each domain stores all its cookies in a single string, which can make
parsing data difficult
Data is unencrypted, which becomes an issue because... ... though
small in size, cookies are sent with every HTTP request Limited size
(4KB)
Local storage
Pros
Support by most modern browsers
Persistent data that is stored directly in the browser
Same-origin rules apply to local storage data
Is not sent with every HTTP request
~5MB storage per domain (that's 5120KB)
Cons
Not supported by anything before: IE 8, Firefox 3.5, Safari 4, Chrome 4, Opera 10.5, iOS 2.0, Android 2.0
If the server needs stored client information you purposely have
to send it.
localStorage usage is almost identical with the session one. They have pretty much exact methods, so switching from session to localStorage is really child's play. However, if stored data is really crucial for your application, you will probably use cookies as a backup in case localStorage is not available. If you want to check browser support for localStorage, all you have to do is run this simple script:
/*
* function body that test if storage is available
* returns true if localStorage is available and false if it's not
*/
function lsTest(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
/*
* execute Test and run our custom script
*/
if(lsTest()) {
// window.sessionStorage.setItem(name, 1); // session and storage methods are very similar
window.localStorage.setItem(name, 1);
console.log('localStorage where used'); // log
} else {
document.cookie="name=1; expires=Mon, 28 Mar 2016 12:00:00 UTC";
console.log('Cookie where used'); // log
}
"localStorage values on Secure (SSL) pages are isolated"
as someone noticed keep in mind that localStorage will not be
available if you switch from 'http' to 'https' secured protocol, where
the cookie will still be accesible. This is kind of important to
be aware of if you work with secure protocols.

Cookies:
Introduced prior to HTML5.
Has expiration date.
Cleared by JS or by Clear Browsing Data of browser or after expiration date.
Will sent to the server per each request.
The capacity is 4KB.
Only strings are able to store in cookies.
There are two types of cookies: persistent and session.
Local Storage:
Introduced with HTML5.
Does not have expiration date.
Cleared by JS or by Clear Browsing Data of the browser.
You can select when the data must be sent to the server.
The capacity is 5MB.
Data is stored indefinitely, and must be a string.
Only have one type.

Key Differences:
Capacity:
Local Storage: 10MB
Cookies: 4kb
Browser Support:
Local Storage: HTML5
Cookies: HTML4, HTML5
Storage Location:
Local Storage: Browser Only
Cookies: Browser & Server
Send With Request:
Local Storage: Yes
Cookies: No
Accessed From:
Local Storage: Any Window
Cookies: Any Window.
Expiry Date:
Local Storage: Never Expire, until done by javascript.
Cookies: Yes, Have expiry date.
Note: Use that, what suits you.

It is also worth mentioning that localStorage cannot be used when users browse in "private" mode in some versions of mobile Safari.
Quoted from WayBack Archive of MDN topic on Window.localStorage back in 2018:
Note: Starting with iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short. Safari Mobile's Private Browsing mode also prevents writing to localStorage entirely.

Cookie:
is accessible by JavaScript so Cookie's data can be stolen by XSS
attack(Cross Site Scripting attack) but setting HttpOnly flag
to Cookie prevents the access by JavaScript so Cookie's data is
protected from XSS attack.
is vulnerable to CSRF(Cross Site Request Forgery) but setting
SameSite flag with Lax to Cookie mitigates CSRF and setting SameSite flag with Strict to Cookie prevents
CSRF.
must have expiry date so when expiry date passes, Cookie is
deleted automatically so even if you forgot to delete Cookie,
Cookie is deleted automatically because of expiry date.
is about 4KB as a common size (depending on browsers).
Local Storage:
is accessible by JavaScript so Local Storage's data can be stolen by XSS
attack(Cross Site Scripting attack) then, as logn as I researched,
there are no easy preventions for Local Storage from XSS
attack.
is not vulnerable to CSRF(Cross Site Request Forgery).
doesn't have expiry date so if you forgot to delete Local Storage
data, Local Storage data can stay forever.
is about 5MB as a common size (depending on browsers).
I recommend using Cookie for sensitive data and Local Storage for non-sensitive data.

Well, local storage speed greatly depends on the browser the client is using, as well as the operating system. Chrome or Safari on a mac could be much faster than Firefox on a PC, especially with newer APIs. As always though, testing is your friend (I could not find any benchmarks).
I really don't see a huge difference in cookie vs local storage. Also, you should be more worried about compatibility issues: not all browsers have even begun to support the new HTML5 APIs, so cookies would be your best bet for speed and compatibility.

Local storage can store up to 5mb offline data, whereas session can also store up to 5 mb data. But cookies can store only 4kb data in text format.
LOCAl and Session storage data in JSON format, thus easy to parse. But cookies data is in string format.

Related

Is using cookies to store minor details of the client better than local storage?

I'm using cookies for most important details like tokens. They are secure and httpOnly. I have a few more details to save on the client side. Like, once the user logs in, I'm storing the userType (customer | internal user) and a few flags that are set true/false. I'm storing these additional details in the local storage because they are being used by the client for some basic tasks. Is it a good idea to move them to Cookies keeping their httpOnly : false (as the browser JS can only access cookies without httpOnly) ?
Cookies are transferred by the client to the server on every request. If the data being transferred is something that the server frequently has to access - like a session cookie, so that the server can easily tie a given request with a particular user and their credentials/settings - that's the perfect situation for using a cookie. httpOnly makes it more secure because only the server can read it.
If the data you want to store is not often read by the server, then cookies may not be the right choice, because cookies get sent by the client on every request; putting the data into cookies could be resulting in unnecessary overhead.
For data that the client needs to send that's security sensitive, like a session token, I'd recommend cookies with httpOnly, because that'll make possible XSS attacks much more difficult to execute.
For data that isn't security sensitive - like layout preferences - storing it in Local Storage will definitely make more sense if the data is only read/written by the client.
For your situation, consider whether the userType and other flags are essential to keep secret - it sounds like they may not be. Then, if they're only used by the client, Local Storage is the more appropriate choice. If the server does occasionally need use of them, you could put it into non-httpOnly cookies - or not, whatever makes your workflow easier.
Do you use a central FE data store like Redux or Apollo? Personally I would set userType in a FE data store like that.
For cookies that you would set as httpOnly: false. The security is roughly equivalent between cookies and local storage. If a malicious script was run on your site, the script would be able to access local storage and non-secure cookies.

Where and how save token JWT ? (Best Practice)

I've read that save token JWT in localStorage is a bad practice.
https://dev.to/rdegges/please-stop-using-local-storage-1i04
I'm working with ReactJs, and to other side have a API Rest with NodeJs.
Where and how I should save token JWT ?, in a Cookie?
Gretting from Chile,
If the choice is between cookie and localStorage, both have their pros and cons when it comes to security. With all security attributes set correctly (HttpOnly, secure, SameSite=strict) it is true that a cookies could be more protected against certain attacks.
However, SameSite attributes may not work for everyone, and may not protect all functions against CSRF (Cross Site Request Forgery) attacks.
HttpOnly will protect the value from being accessed from JavaScript which is good if the application suffers (XSS) Cross Site Scripting vulnerabilities. However, any moderately qualified attacker could easily achieve what they wanted without accessing the actual value of the token anyway.
The thing to remember when storing tokens in localStorage is that it is not cleared when the browser is closed, meaning that a user will not become logged out by closing the browser - which many have come to expect. If that is a problem, you may want to consider storing the JWT in the sessionStorage instead.
localStorage seems fine because many people are using localStorage.
If you want extra security feature
You can make your token lifespan short eg {30 min, 60 min}
Also You can check your user active state whether or not
The user will Logout automatically

Store details from form into session for authentication [duplicate]

What are the technical pros and cons of localStorage, sessionStorage, session and cookies, and when would I use one over the other?
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
Pros:
Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. If you look at the Mozilla source code we can see that 5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.
The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
Cons:
It works on same-origin policy. So, data stored will only be available on the same origin.
Cookies
Pros:
Compared to others, there's nothing AFAIK.
Cons:
The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.
Typically, the following are allowed:
300 cookies in total
4096 bytes per cookie
20 cookies per domain
81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.)
sessionStorage
Pros:
It is similar to localStorage.
The data is not persistent i.e. data is only available per window (or tab in browsers like Chrome and Firefox). Data is only available during the page session. Changes made are saved and available for the current page, as well as future visits to the site on the same tab/window. Once the tab/window is closed, the data is deleted.
Cons:
The data is available only inside the window/tab in which it was set.
Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.
Checkout across-tabs - how to facilitate easy communication between cross-origin browser tabs.
OK, LocalStorage as it's called it's local storage for your browsers, it can save up to 10MB, SessionStorage does the same, but as it's name saying, it's session based and will be deleted after closing your browser, also can save less than LocalStorage, like up to 5MB, but Cookies are very tiny data storing in your browser, that can save up 4KB and can be accessed through server or browser both...
I also created the image below to show the differences at a glance:
here is a quick review and with a simple and quick understanding
from instructor Beau Carnes from freecodecamp
These are properties of 'window' object in JavaScript, just like document is one of a property of window object which holds DOM objects.
Session Storage property maintains a separate storage area for each given origin that's available for the duration of the page session i.e as long as the browser is open, including page reloads and restores.
Local Storage does the same thing, but persists even when the browser is closed and reopened.
You can set and retrieve stored data as follows:
sessionStorage.setItem('key', 'value');
var data = sessionStorage.getItem('key');
Similarly for localStorage.
Exact use case -
If you want your page to always hold some data that is not confidential, then you can use localStorage.
If the server needs to know some information like authentication keys, you should use cookies to store them.
sessionStorage can be used to store the state of the interface, i.e., whenever you visit a page, customize it, visit another page and return to the same page, you would want to show the page how the user customized it. That’s a good use case for sessionStorage.
The Web Storage API provides mechanisms by which browsers can securely store key/value pairs, in a much more intuitive fashion than using cookies.
The Web Storage API extends the Window object with two new properties — Window.sessionStorage and Window.localStorage. — invoking one of these will create an instance of the Storage object, through which data items can be set, retrieved, and removed. A different Storage object is used for the sessionStorage and localStorage for each origin (domain).
Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads.
localStorage.colorSetting = '#a4509b';
localStorage['colorSetting'] = '#a4509b';
localStorage.setItem('colorSetting', '#a4509b');
The keys and the values are always strings. To store any type convert it to String and then store it. It's always recommended to use Storage interface methods.
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('Converting String to Object: ', JSON.parse(retrievedObject));
The two mechanisms within Web Storage are as follows:
sessionStorage maintains a separate storage area for each given originSame-origin policy that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
localStorage does the same thing, but persists even when the browser is closed and reopened.
Storage « Local storage writes the data to the disk, while session storage writes the data to the memory only. Any data written to the session storage is purged when your app exits.
The maximum storage available is different per browser, but most browsers have implemented at least the w3c recommended maximum storage limit of 5MB.
+----------------+--------+---------+-----------+--------+
| | Chrome | Firefox | Safari | IE |
+----------------+--------+---------+-----------+--------+
| LocalStorage | 10MB | 10MB | 5MB | 10MB |
+----------------+--------+---------+-----------+--------+
| SessionStorage | 10MB | 10MB | Unlimited | 10MB |
+----------------+--------+---------+-----------+--------+
Always catch LocalStorage security and quota exceeded errors
QuotaExceededError: When storage limits exceeds on this function window.sessionStorage.setItem(key, value);, it throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.)
DOMException.QUOTA_EXCEEDED_ERR is 22, example fiddle.
SecurityError : Uncaught SecurityError: Access to 'localStorage' is denied for this document.
CHROME:-Privacy and security « Content settings « Cookies « Block third-party cookies.
StorageEvent « The storage event is fired on a document's Window object when a storage area changes. When a user agent is to send a storage notification for a Document, the user agent must queue a task to fire an event named storage at the Document object's Window object, using StorageEvent.
Note: For a real world example, see Web Storage Demo. check out the source code
Listen to the storage event on dom/Window to catch changes in the storage. fiddle.
Cookies (web cookie, browser cookie) Cookies are data, stored in small text files as name-value pairs, on your computer.
JavaScript access using Document.cookie
New cookies can also be created via JavaScript using the Document.cookie property, and if the HttpOnly flag is not set, existing cookies can be accessed from JavaScript as well.
document.cookie = "yummy_cookie=choco";
document.cookie = "tasty_cookie=strawberry";
console.log(document.cookie);
// logs "yummy_cookie=choco; tasty_cookie=strawberry"
Secure and HttpOnly cookies HTTP State Management Mechanism
Cookies are often used in web application to identify a user and their authenticated session
When receiving an HTTP request, a server can send a Set-Cookie header with the response. The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header.
Set-Cookie: <cookie-name>=<cookie-value>
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>
Session cookies will get removed when the client is shut down. They don't specify the Expires or Max-Age directives.
Set-Cookie: sessionid=38afes7a8; HttpOnly; Path=/
Permanent cookies expire at a specific date (Expires) or after a specific length of time (Max-Age).
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly
The Cookie HTTP request header contains stored HTTP cookies previously sent by the server with the Set-Cookie header. HTTP-only cookies aren't accessible via JavaScript through the Document.cookie property, the XMLHttpRequest and Request APIs to mitigate attacks against cross-site scripting (XSS).
Cookies are mainly used for three purposes:
Session management « Logins, shopping carts, game scores, or anything else the server should remember
Personalization « User preferences, themes, and other settings
Tracking (Recording and analyzing user behavior) « Cookies have a domain associated to them. If this domain is the same as the domain of the page you are on, the cookies is said to be a first-party cookie. If the domain is different, it is said to be a third-party cookie. While first-party cookies are sent only to the server setting them, a web page may contain images or other components stored on servers in other domains (like ad banners). Cookies that are sent through these third-party components are called third-party cookies and are mainly used for advertising and tracking across the web.
Cookies were invented to solve the problem "how to remember information about the user":
When a user visits a web page, his name can be stored in a cookie.
Next time the user visits the page, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.
GitHubGist Example
As summary,
localStorage persists over different tabs or windows, and even if we close the browser, accordingly with the domain security policy and user choices about quota limit.
sessionStorage object does not persist if we close the tab (top-level browsing context) as it does not exists if we surf via another tab or window.
Web Storage (session, local) allows us to save a large amount of key/value pairs and lots of text, something impossible to do via cookie.
Cookies that are used for sensitive actions should have a short lifetime only.
Cookies mainly used for advertising and tracking across the web. See for example the types of cookies used by Google.
Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web storage API (localStorage and sessionStorage) and IndexedDB.
Local storage: It keeps store the user information data without expiration date this data will not be deleted when user closed the browser windows it will be available for day, week, month and year.
In Local storage can store 5-10mb offline data.
//Set the value in a local storage object
localStorage.setItem('name', myName);
//Get the value from storage object
localStorage.getItem('name');
//Delete the value from local storage object
localStorage.removeItem(name);//Delete specifice obeject from local storege
localStorage.clear();//Delete all from local storege
Session Storage: It is same like local storage date except it will delete all windows when browser windows closed by a web user.
In Session storage can store upto 5 mb data
//set the value to a object in session storege
sessionStorage.myNameInSession = "Krishna";
Session: A session is a global variable stored on the server. Each session is assigned a unique id which is used to retrieve stored values.
Cookies: Cookies are data, stored in small text files as name-value pairs, on your computer. Once a cookie has been set, all page requests that follow return the cookie name and value.
LocalStorage:
Web storage can be viewed simplistically as an improvement on
cookies, providing much greater storage capacity. Available size is
5MB which considerably more space to work with than a typical 4KB
cookie.
The data is not sent back to the server for every HTTP request
(HTML, images, JavaScript, CSS, etc) - reducing the amount of
traffic between client and server.
The data stored in localStorage persists until explicitly deleted.
Changes made are saved and available for all current and future
visits to the site.
It works on same-origin policy. So, data stored will only be
available on the same origin.
Cookies:
We can set the expiration time for each cookie
The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.
sessionStorage:
It is similar to localStorage.
Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted
The data is available only inside the window/tab in which it was set.
The data is not persistent i.e. it will be lost once the window/tab is closed. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.
localStorage
data stored with localStorage has no expiration date, and gets cleared only through JavaScript, or clearing the Browser cache / Locally Stored Data.
The storage limit is the maximum amongst the three.
The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
It works on the same-origin policy. So, data stored will only be available on the same origin.
sessionStorage
It stores data only for a session, meaning that the data is stored until the browser (or tab) is closed.
Data is never transferred to the server.
Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted.
I would expect that sessionStorage would be faster as it doesn’t need to write to the disk (lacking persistency). But my simple console tests shows that they are equal in performance 😔
let item = 500000;
const start = Date.now();
while(item) {
sessionStorage.setItem('testKey', item);
item = parseInt(sessionStorage.getItem('testKey'));
item--;
}
console.log('SessionStorage PERF: (lower is better)', Date.now() - start);
same code for local storage
let item = 500000;
const start = Date.now();
while(item) {
localStorage.setItem('testKey', item);
item = parseInt(localStorage.getItem('testKey'));
item--;
}
console.log('LocalStorage PERF: (lower is better)', Date.now() - start);
results:
SessionStorage PERF: (lower is better) 2889
SessionStorage PERF: (lower is better) 2852
LocalStorage PERF: (lower is better) 2807
LocalStorage PERF: (lower is better) 2889

Is http-only cookie safe?

I am setting http-only cookie from the server for storing some user info so that i can validate user on backend. Say some hacker steals this cookie from someone's browser and go to my webpage and add the same cookie using document.cookie = "cookie_name = cookie_value" if cookie is not there. If cookie is there then he can delete the existing http-only cookie using chrome developer tool and later add it using document.cookie = "cookie_name = cookie_value" on his browser.
Now when server gets a call from hacker browser, it gets a cookie set by hacker and would validate it. How can i stop this?
Cookies leave you vulnerable to Cross-Site Request Forgeries and their kin. Not just hackers stealing cookies, but hackers borrowing a user's browser which already has the cookies. This is part of why tokens are more common today.
If you have to use cookies, there are various things you can do to make them slightly less insecure--updating the cookie on each request, verifying request IP against sending IP, configuring your web pages not to allow the loading off offsite content, forcing re-login for any major actions, and other user verification means. None of them is perfect.
Simple: You cannot. http-only serves a different purpose than validation. Your assumption that a hacker will use a browser is the first problem you have. I would never use a browser for something like that since a browser would restrict me. I would forge a HTTP request with my own tools and send a header with http-only and secure and whatever you want me to to your server.
If you want to validate your cookies, you will need to implement your own solution instead of relying on browser mechanisms. You could for example bind the cookie to a certain IP range and add some kind of token to the end of the cookie-key or cookie-value.
In general, do what #bryanx says. DO NOT USE COOKIES TO STORE DATA. They are fine for session tokens and the like.
Don't use cookies.
Cookies are necessary for preserving information between sessions, but any time you leave information on the client, you open yourself up to potential issues like you described. If you only need the information maintained during the user's session, you may want to consider using a $_SESSION instead of a cookie.
If you must use cookies, you may want to consider building out logic that if the cookie doesn't match a previously authenticated device, that you challenge the user again for their credentials. There are many ways to solve for this, just get creative.

How persistent is localStorage?

I'm depending heavily on localStorage for a plugin I'm writing. All the user settings are stored in it. Some settings require the user the write regex'es and they would be sad if their regex rules are gone at some point.
So now I am wondering just how persistent the localStorage is.
From the specs:
User agents should expire data from the local storage areas only for security reasons or when requested to do so by the user.
The above looks like it works just like cookies on the clientside. I.e. when the user clears all browser data (history, cookies, cache etc) the localStorage will also be truncated. Is this assumption correct?
Mozilla implements it like cookies:
DOM Storage can be cleared via "Tools -> Clear Recent History -> Cookies" when Time range is "Everything" (via nsICookieManager::removeAll)
https://developer.mozilla.org/en/DOM/Storage
In DOM Storage it is not possible to specify an expiration period for any of your data. All expiration rules are left up to the user. In the case of Mozilla, most of those rules are inherited from the Cookie-related expiration rules. Because of this you can probably expect most of your DOM Storage data to last at least for a meaningful amount of time.
http://ejohn.org/blog/dom-storage/
Chrome implements it like cache:
LocalStorage is Not Secure Storage
HTML5 local storage saves data unencrypted in string form in the regular browser cache.
Persistence
On disk until deleted by user (delete cache) or by the app
https://developers.google.com/web-toolkit/doc/latest/DevGuideHtml5Storage
As for a "replacement for the Cookie", not entirely
Cookies and local storage really serve difference purposes. Cookies are primarily for reading server-side, LocalStorage can only be read client-side. So the question is, in your app, who needs this data — the client or the server?
Basically, you should not heavily depend on Local Storage.
Local Storage, along with Session Storage, aims to be a replacement of the cookies, defining a more consistent API. There are a few differences from the cookies:
While the cookies are accessible from both client and server side, Web Storage, in general, and Local Storage, in particular, are accessible only from client side.
Enhanced capacity (official for cookies is 4 KB) to more than 5MB per domain (Firefox, Google Chrome, and Opera and 10MB in IE).
So yes, your assumption is correct.
One thing to note about using local storage. It is very browser specific. If you store data with firefox it won't be available in chrome or ie etc. Also as far as clearing cookies and sessions, I've noticed it is also browser specific as to whether or not the local storage is cleared. I'd look into the details a lot if you're really planning on relying on local storage for an app.
Local Storage is designed to be a dependable, persistent store of data on a client. It is not designed as a "better cookie": that function is designed to be met by Session Storage.
From the Dec 2011 Web Storage Spec Candidate Recommendation,
(Local Storage) is designed for storage that spans multiple windows,
and lasts beyond the current session. In particular, Web applications
may wish to store megabytes of user data, such as entire
user-authored documents or a user's mailbox, on the client side for
performance reasons.
As client-side data - it is as persistent as any client side data, within the size limits that the browser implements. Users can delete it at any time, open it up in a text editor and edit etc. - just like ANY client side data.
If you're using localStorage for a iOS app, be very careful. THe latest version of iOS (5.1 off the top of my head) has moved localstorage and localdb data to a part of the cache that is regularly cleared, i.e. not at all persistent. I can't tell yet if this is a bug or a policy change.

Categories