What are uses of cookies in web apps? - javascript

I am building a web app and have noticed that other web apps (gmail in particular) use cookies and it logs you out if you don't have cookies enabled. Any idea what these cookies are used for that they are so crucial? Are there any common uses for cookies in web apps?

It enables the server to maintain a client-specific state across requests (session) in the server side. It also enables JavaScript to maintain a client-specific state across requests in the client side without need for server interaction.

A cookie is a small piece of data (name-value pair) sent from a website (sever side) and stored in a user's web browser while the user is browsing that website. Cookies were designed to provide stateful information about user interaction in spite the stateless nature of HTTP protocol. Cookies can be categorised based on its nature.
Types of cookie can be selected based on the capabilities you want the cookie to have.
Session cookie
A session cookie, also known as an in-memory cookie or transient cookie, exists only in temporary memory, while the user navigates the website. (In java, Session cookie can be created by calling getSession() on request object). Web browsers normally delete session cookies when the user closes the browser. This type of cookies may be used to maintain data related to the user during navigation but in the same session. User can go back and forth on website without affecting the preferences but the moment browser is shut down or session timeout, all preferences will be lost.
Persistent cookie
A persistent cookie outlasts user sessions if you does not set the max-age. To retain the cookie beyond the user session, you have to set Max-Age for that cookie. Cookie must have data (name-value pair) which will sent back to the server every time the user visited the website. This could be used to record a vital piece of information such as how the user initially came to this website or the preferences made etc. Persistent cookies may be used to maintain data related to the user during navigation, possibly across multiple visits in different time. Persistent cookies store user related data which will be used for future visit to website. Persistent cookie can be used as shopping cart to which users can store items they want to purchase as they navigate throughout the site or in future.
Secure cookie
A secure cookie has the secure attribute enabled and is only used via HTTPS, ensuring that the cookie is always encrypted when transmitting from client to server. This makes the cookie less likely to be exposed to cookie theft via eavesdropping. In addition to that, all cookies are subject to browser's same-origin-policy.
As you asked about Gmail cookie mechanism, yes Gmail is using this secure cookie mechanism to store username and random token as your credentials to login. Yes, it is not storing your original password in secure cookie instead when you successfully enter the correct username and password and say yes to remember my password, it generates a random number (token) for your username as a login cookie issued in addition to the standard session management cookie and store username and random number as password in its database. That cookie cannot be used by other device as it is using same-origin-policy. The username and token are stored as a pair in a database table. When a user again visits the site, the login cookie will be sent to the server in the request object automatically from browser, then the username and token are verified in the database by the server. If the pair is present, the user is considered authenticated. The used token is removed from the database. A new token is generated and stored in database with the username, and issued to the user via a new login cookie in the response object. If the pair is not present, the login cookie is ignored. Users entered via this mechanism are not permitted to access certain protected information or functions such as changing a password, viewing Personally Identifiable Information (PII). To perform those operations, the user must first successfully submit a normal username/password login form which will pop automatically when you tried to do these prohibited operations. Since this approach allows the user to have multiple remembered logins from different browsers or computers.
HttpOnly cookie
The HttpOnly attribute is supported by most modern browsers. On a supported browser, an HttpOnly session cookie will be used only when transmitting HTTP (or HTTPS) requests, thus restricting access from other non-HTTP APIs such as JavaScript. This restriction mitigates but does not eliminate the threat of session cookie theft via cross-site scripting (XSS). This feature applies only to session-management cookies and not on other browser cookies.
Third-party cookie
Third-party cookies are cookies that belong to domains different from the one shown in the address bar. It is mostly used for advertisement by keeping tracks of user preferences and browser history to judge its inclination and sell him something accordingly.

Cookies maintain data that pertains to the user, and it resides on the user's computer (i.e. browser cookies), so that it gets loaded when they come back to the site, even after a few days, or even much longer than days.
Here are some examples of information that makes sense the most to be in a cookie:
The user's choice of ordering in a column
The user's color theme of a web page
The user's preference of article categories (such as Google News sections)
You might say "why not save it in a database and have the server handle it?"
Well, cookies also allow you to maintain a user's preferences without requiring them to create an account that will track their settings.
You might also say "why not keep it in the Session of the web app (such as in ASP.NET)?"
The Session is wiped when the user leaves the site, so the settings won't last until they come back again.

As others have said Cookies are used for maintaining state. The meta-reason why they're used is because HTTP is a stateless protocol but business reality demands state persistance somehow.

One thing not mentioned so far is that cookies are also used to store authentication information (as well as application state). This would explain why you're automatically logged out on gmail when you turn cookies off. If google can no longer determine which user you are, then they can't give you access to your email.

Cookie is data set by server and presented by UA to the server on each request. The purpose is to preserve state between requests (remember, HTTP is stateless protocol). This give a broad range of uses, from keeping simple preferences to identifying particular UA amongst the others (that how GMail identifies you and your account when you logged in)

Related

Is it a secure way to handle returning user in ember?

I am using ember to write a web ui for a site that requires user to log in. Suppose the browser has stored some cookie from last login of a user. Now the user visits the site again. So, is it a secure and common way for ember to log the user in automatically based on the cookie from the last visit? If so, what are the common ways to implement this? (I can't find anything from Google.) Furthermore, how do I create the cookie upon login? Is it a common way to just put a user id, password hash, and expiration in the cookie?
Additionally, any references related to this subject are greatly appreciated.
Edit 1
In light of Vohuman's answer, I think I can make my question a little more specific. Basically, what I want to know is a common and secure implementation to keep a user logged in, even when they close and reopen the browser. Namely, the life time is beyond the session scope. Take linkedin for example. If you are logged in and exit the browser. Then next time you revisit linkedin, you are still logged in automatically. Right now, what I can picture is a solution like the following.
When you first log in to the site, the server will return a cookie which includes an authentication hash token. Then next time when you revisit the site, the server will receive the hash token and thus authenticate your session.
So, is above flow basically what people usually do to keep a user logged in? If so, is the JSON Web Token (JWT) basically one way to construct the hash token I mentioned above? Additionally, assuming the connection is HTTPS, this approach seems secure to me. Is it not?
Edit 2
This article gives an interesting discussion regarding where to store the access token.
is it a secure and common way for ember to log the user in automatically based on the cookie from the last visit?
Yes and no. Security is a complex topic. Usually session cookies are used for authorizing users. This is actually the most used method of keeping the users logged in. If the user can't keep his credentials secure then any layers of security can be vulnerable.
For Single-page applications usually access tokens are used instead of cookies and sessions. The client sends the user credentials and server returns an access token. The token is encrypted and expirable and can be stored in localStorage or sessionStorage. Using JSON Web Tokens (JWT) standard is a popular method for implementing user authentication and authorization in web services. As an example, the Facebook Open Graph API uses access tokens.
JSON Web Token (JWT) is a compact, URL-safe means of representing
claims to be transferred between two parties. The claims in a JWT
are encoded as a JSON object that is used as the payload of a JSON
Web Signature (JWS) structure or as the plaintext of a JSON Web
Encryption (JWE) structure, enabling the claims to be digitally
signed or integrity protected with a Message Authentication Code
(MAC) and/or encrypted.
edit:
So, is above flow basically what people usually do to keep a user logged in?
For traditional websites, yes.
The whole point of using access tokens is keeping the web service/API stateless. This means that server doesn't have to store any cookies/sessions for authenticating and authorizing users. The stateless is one of the key factors of implementing web services that follow the REST paradigm. It's client that has to store the token and send it to the server (via the Authorization header or query parameters). The server doesn't store the token. Of course, you can store the tokens on the server if you want to add another layer of security, but it's not so common and not necessary. Storing the tokens on the server can also make your application vulnerable to database attacks and is not recommended.
If you want to make the process more secure you can decrease the validity time of access tokens (1 hour, 1 day or 1 week, it's up to you).
As for localStorage, is it secure?
localStorage data are stored separately for each origin (domain). A malicious user can only read the data if he/she has access to the user browser. You should make sure that your app doesn't have any XSS vulnerabilities so malicious users can't inject any scripts to your application. This is actually a different topic.

Are there any security concerns storing HTTP Basic authorization header in localStorage?

I'm building a web application that accesses a private API. The API that I'm consuming uses HTTP Basic Authentication over TLS. My client has requested a "remember me" functionality for the web app so that users can maintain persistent authentication on a given device.
My quick-and-dirty solution is to store the Authorization header in localStorage after it has been validated. Of course, given unmitigated access to a user's device, anybody who is worth their weight in salt could copy the auth header from localStorage and decode it to retrieve the user's login/password combo.
Aside from total device compromise, are there any other security implications from storing this type of sensitive data in localStorage? Is localStorage acceptable as a store for sensitive data such as passwords? If not, how would you persist such data on a user's device beyond an individual browser session?
(I wish everybody could just use his or her private key...passwords are so 90s)
EDIT After reading HTML5 localStorage security it seems clear that storage of sensitive data in localStorage in general is a bad idea, but what better option is there for authentication persistence in this case?
I think it's a bad idea to store something related to the login or the password on the user's side.
But once an user has logged in, you can store a random string (a random hash for example) on the user's side and in your database. When the user get back, you can compare the two and if they are identical, you can log in the user. And you can ask the user to enter his password for sensitive actions (change password or login, etc.). So even if the hash is stolen, no one will be able to get the full access to this account.
Edit : this concept is already used with cookies. I've never tested it with localStorage.

how to prevent cookie from being stolen and user on other browser and system

currently I'm working with cakephp and implementing user management in my project.
today, i came across an issue in user session.
i have generated a cookie to remember user's password in encrypted format
The cookie restores session if users session goes expired.
now i have tried transferring cookie to other browser from chrome to Mozilla
using a cookie manager plugin.
and i have found myself logged in in both browser what is the best way to prevent this.
??
You can't prevent this. However, you can reduce the problem by having a session value generated server-side when the user starts a new session, which is some hash made from
The session ID
The user agent (attacker would have to use/spoof the same client)
Possibly the IP (would only work for fixed devices, but makes it much harder for an attacker)
Now when a logged in user tries to view a page requiring you to be logged in, you can compare more details than just the session lookup.
It's not impossible to spoof, but this reduces the problem.
This hash should never be actually sent to the client, just kept in the session information server-side.

Local Storage vs Cookies: save and send user credentials via websockets

I have: websocket secure connection (wss) through the whole app. + Backbone.js on client side if it's significant.
I want: automatically log in user on new tab opening, if he's already logged in another tab.
Question: what is better either use cookies or localStorage?
If you use localStorage, the user's credentials will be stored (presumable unencrypted unless you implement this yourself) on the user's local machine. These records will not expire unless you write your application to do this. As such your user would be logged in forever, not just if they have another tab open, unless you also wrote logic for that. But there is no reason to do all this additional work.
Cookies are already frequently used to accomplish this functionality. Inside the cookie you should store a session token, which identifies the user's session uniquely. Cookies have the advantage of automatic expiration, and are automatically passed to the server with each HTTP request. For more information about the differences between cookies and localStorage, take a look at this thread.

Using httpOnly cookies for device registration

I have a mobile website where, as part of my security measures, I want users to "register" their device, so I can limit the number of devices that users can have accessing the site. My thought was, for a "new" device, put them through a two-factor authentication process, and store a server-sent GUID in an httpOnly cookie (over SSL) which will hold the GUID. When the user comes to the site and logs in using their username and password, the server will compare that cookie against their user record in the database, and if it's a match let's them log in.
So my question is: is this a valid/secure use of httpOnly cookies? Does the method that I'm describing for "device registration" make sense?
Thanks!
This would stop casual users from using multiple devices with your service, but it would be easy to circumvent as they could copy the cookie to another device. The HttpOnly flag simply restricts client-side script such as JavaScript from accessing the cookie, it does not prevent the user themselves accessing the cookie or force encryption of it in any way in the cookie jar.
You could make your solution work though with a little bit more engineering: Rolling tokens for each device. By this I mean it would give each client a new device ID on every login, and this mechanism will also invalidate the old one. This would cause a second device with a copy of the original cookie to be no longer able to use your service without separate registration and a count against your device limit.
Also, it might be better to use something other than GUIDs depending on the level of security needed as they are possibly predictable:
How secure are GUIDs in terms of predictability?
Are GUIDs safe for one-time tokens?

Categories

Resources