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

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.

Related

How to detect another session is ongoing from another browser tab using Parse Server error

I'm trying to auto logout an app if user logged in from another tab or browser.
I'm using react-idle-timer and Parse Server.
I'm not sure if this line of code will be useful
Parse.Error.INVALID_SESSION_TOKEN
I can access session token via localStorage
const res = await Parse.Cloud.run('login', values);
console.log(res.session);
You can't differentiate a request from a different tab within the same browser. It will share the same session token and be indistinguishable from any other request. Requests made from different browsers will have different session tokens and if they store some user info you can determine which ones belong to which user.
If we reframe your question it sounds like you only want to allow for one active login per user. This requires a centralized or clustered session management solution that supports preventing multiple concurrent sessions.
If you will only ever have one backend server or you are using a shared database to store sessions, then you can do this a bit easier depending on what you are using for session management since all sessions will be available on the one server.
It is not clear to me if your users are connecting directly to parse server. If they are you will most likely need to modify parse-servers code directly to support this.
In general this is a silly idea. Unless you have a legal requirement to do so I would not advocate worrying about this. Bypassing this is usually as easy as copying around a session token.

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.

Logout of application on clearing browser history

I have an application, I want to logout of it if user manually clears browser history, as it happens in "facebook" or "gmail", is their any event which notifies my application about this.
Need help,as I am new to web application development.
Usually such applications store user information e.g. login details, session time etc on client side in cookies. Once you reset browser history, it deletes all cookies and temp files.
So, using client side Cookies can be solution to your problem.
If you're using PHP, you can use addcookie() to set cookie values and expiration dates. If the expiration date is false, then the cookie is deleted on session close (when you close the browser). Otherwise, it's set to expire on a certain day. These cookies are stored on the user's computer and can be changed/viewed by the user.
You can also use JavaScript to manipulate cookies like $.cookie() or document.cookie if you don't have jQuery.
if that helps

Storing Credentials in Local Storage

Could I securely use local storage instead of cookies to store session credentials?
Would I need to store an encrypted hash??
EDIT: Would this be secure enough?
User logs in.
Server returns success message including salted bcrypt hash mixing userid, password, timestamp, and possibly ip address. This is saved in local storage.
On future connects this hash is sent, server assumes accountability as long as IP address hasn't changed, and time limit hasn't expired.
localstorage is just as vulnerable to being read by JavaScript as cookies are.
localstorage can be read using JavaScript from the same domain, if you control all the JS on the domain, then this shouldn't be a problem. But if any other code is executed (via injection for example, or if you share the domain with someone else), they will be able to access the storage data.
This is the same for cookies however, but typically the cookie is set to HTTPOnly so JavaScript cannot read it.
In either case, plain-text login information shouldn't be stored in either cookies or localstorage anyhow, as if someone does get hold of them, they can continuously make a new session for themselves.
You should encrypt an authenticated identifier (such as their user ID) along with the datetime of the session expiration, and then store this value in either a cookie or local storage. This token is then validated on each server call.
If you're going to be using local storage, why store user credentials or anything derived from them at all?
What I've been looking into doing is:
Upon successful login, generate a completely random string unrelated to user credentials and store that in the database, along with an expiry date. I would then pass that string to my js to be stored in local storage.
From then on, so long as that local storage credential matches the database one and the timeout has not expired, I automatically consider them logged in.
This way, there is no risk concerning the exposure of the user's credentials from local storage. However, with this temporary unique string essentially functioning as a sessionID, you will still to need to be aware of and take precautions against the risks associated with session hijacking.
In any case, my understanding is that local storage is as secure as the server behind your site is. By that I mean local storage is only accessible via scripts coming in through your own domain, so you're safe so long as the only front code running is your own.
You server shall generate some token - unique (for the server) piece of data that cannot be used to discover username/password. Only that token can be stored on user's machine in any form. Neither localStorage nor cookie are secure. So the same rules applied to them in this respect.
You should have some means to expire such token otherwise once stolen such token can be used instead of real credentials.
If you're going to use localStorage instead of cookies, you can make things more secure than cookies. That's because you don't need to send a session id to the server with each request, making it a bearer token. Instead, you can store a user secret on the client side in localStorage, and use it to sign your requests in addition to the corresponding public key being sent down and used as the session id. This way, no one on the server side or proxy can fake your requests.

What are uses of cookies in web apps?

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)

Categories

Resources