User Authentication with Cookies Only - authentication

I am planning to use only cookies (and not sessions) to authenticate users around the private section of my website. I want users to stay logged in indefinitely, unless they logout themselves. It will work like this:
1. Upon successful login I generate a random hash and store it as a HTTP cookie on the user (using SSL). I also store the hash in my database, along with the user id and the user's device.
2. Whenever a new page is requested I check to see if the user has a cookie. If he has I get the hash and search it in my database. If I find a match and the device is the same I assume it's the user and give the page. If I can't find the hash or the device changed I assume it's not the user and ask for login again.
My question: would this method be acceptable, security-wise? I can't see why this would be less secure than using sessions (keeping the users logged in in both cases), as in the end the risk is the same, which is having an attacker discover the hash to impersonate the user. My defense against this is tracking the users device, so the attacker would need to discover the hash and have the same device.
Thanks for your feedback.

What you're describing is basically the session functionality offered by most languages/frameworks.
Just make sure your hash values don't use the time the user logged in as a source of entropy, ie. don't use h(username + login_time) because this could be brute forced fairly easily if the attacker knew the approximate login time.
What language / framework are you actually using? You'll find in most cases there's an option to use the session "functionality" with a persistent cookie (rather than a session one) which would save you implementing this from scratch and possibly creating additional security concerns.

Related

Recommended simple access token expire handling for app

I have a set of APIs purely for my own app, so I just have a simple API to create access token, when user provided the email and password
/api/access_token (return access_token when email and password matched)
The access_token was saved and matched against in the database sessions table with the expiry field, for now, the expiry is one week, so user need to re-login after one week.
So far it worked fine, but if I want to have the remember me functions as those Facebook / Twitter app, which mean user don't need to re-login so often, which I assume they are using something like the OAuth refresh access tokens approach.
Since I am not using those OAuth stuffs, given my current design and setup, what would be the simplest and secure way to achieve the same functionalities?
You have a few options to choose from, I'll try provide an overview. There is a significant difference depending on whether the client is a browser or a mobile app.
First, for browsers, plain old session tokens are generally more secure than JWT or other structured tokens. If your requirements don't force you to store stuff on or flow stuff through the client, then don't.
The most secure option for a browser client (single page javascript app or plain old rendered app) is the following:
When the user hits the login endpoint with their username and password, the endpoint creates a random session id, and stores it in a database.
The server sends back the session token as a httpOnly cookie, thus it protects it from potential XSS.
The client then automatically includes the session token in all subsequent requests.
Additional data can be stored server-side for the session.
This above is basically plain old stateful session management. The length of such a session should be limited, but if your requirements and threat model allows, you can make this a very long session, like months even if you want, but be aware of the associated risk. These tokens can be inspected in the browser and stolen from a user if not else then by physical access to the client, so a very long expiry has its risks.
Note that mobile apps can pretty much just do the same. The difference is that mobile apps do have a way to store secrets more securely on current mobile platforms. As the storage is protected by user login, and also segregated by app, a session id stored correctly in a mobile app has a lot less chance to be compromised, meaning a longer expiry presents lower risk than in case of a plain browser.
You can also implement a refresh token. However, the point in refresh tokens is that you want to store them in a different way than the other token. If they are stored the same way, a refresh token provides very little benefit (sure, it won't be sent with every request, but that's not where it will get compromised anyway, TLS / HTTPS is secure for transport). In case of OAuth / OpenID, the authentication server can for example set the refresh token on its own origin (like login.example.com), and then forward the user to the app with an authorization code for example, which can be exchanged by the application (service provider) for an access token, that is set for the application domain (like app.example.com). This way, the two tokens have different access models, a compromised app will not leak the refresh token, even if the current access token is leaked, and the access token can be refreshed relatively seamlessly.
If you don't have a separate login endpoint, all this doesn't make a lot of sense, except in one very specific case. Thinking about browser clients, you can set a refresh token in a httpOnly cookie, so it's protected from XSS, and you can store an access token in something like localStorage. However, why would you do this? Pretty much the only reason you would do this is if you need to send the access token to some other origin, which is the whole point in OAuth and OpenID.
You could also argue that statelessness is a benefit of such tokens. In reality, the vast majority of services don't actually benefit from statelessness, but it makes some features technically impossible (like for example forcing logout, as in terminating existing user sessions - for that, you would have to store and check revoked tokens, which is not stateless at all).
Ok so to provide "remember me" as in auto-login, you basically have two options. You can either just make your sessions very long (like months, years, forever), which is more ok for mobile apps as they can store the token more securely than a browser, or you can implement some kind of a refresh mechanism. As discussed above, this only makes sense if the refresh token is stored and accessed differently than the session token.
In case of a browser app with a single origin (no auth/login service), this is not really possible, there is no real separation, and a refresh token doesn't make a lot of sense. If you want an auth service, you should be looking into OpenID Connect (OIDC).
For a mobile app, what you could do is store a refresh token in secure storage, and use access tokens from the localStorage of something like a webview, but unless there are very specific requirements, this would likely not be worth the complexity, as you could just store a longer lived session token in the secure storage.
As for remember me, you can just implement it in a way that users that choose to be remembered will have a sessino token with a longer expiry - as you already store expiry for each token in your database, everything is already set up for that, and in many usecases this is fine. There is some additional risk for users that choose this, but there is also some additional benefit in terms of convenience - it's always a compromise.
What you can consider doing to make such very long sessions more secure is check and store some kind of a device fingerprint (there are Javascript libs for this). If you have a very long lived session, but only valid for a specific fingerprint (ie. it only works from the same device), that mitigates the risk somewhat. However, almost everything that is used for a device fingerprint can be spoofed by an attacker, but it still makes it significantly harder for an attacker to steal a session, and you can have approrpiate monitoring in place for attempts. There will be UX considerations too, like the fingerprint might change with browser/app updates and so on, but it's still worth it sometimes.
Another new-ish feature you could consider is WebAuthn and Passkey, for passwordless authentication. These basically provide device authentication, a key will be seamlessly generated for the user on the specific device, and that will be used for logging in. UX is now getting better, but there are still challenges. The way device authentication translates into user authentication is that the key is associated with the user session (the user "unlocks" the keystore, ie. decrypts the stored keys upon login, with their login credentials). This can also provide "remember me" (seamless auto-login), but in my experience the technology is not fully ready yet, though it's getting there.
While I fully agree with the comments above, I would like to create a clear solution in the minds of other readers by giving a clear and directly understandable concrete answer to your problem.
Let's take an example for JWT;
RefreshToken is the structure that will be activated when the AccessToken expires and will complete the Authentication phase without the need for login. The logic is as follows: AccessToken has a very short lifespan compared to RefreshToken. This time is up to you. The purpose is this: AccessToken is destroyed in short time intervals so that it does not fall into the hands of anyone. However, for this reason, the need to login to the system again arises. To make it easier to login again; When you take the previous AccessToken, you will take another token (RefreshToken) that can be used for a longer period of time and keep it in your pocket. The part I call your pocket depends on the technology you use. For example, you can also keep it in the browser. Keeping it in a browser is not an ideal method (It would be DB, file, cache what you use), because it can create a security vulnerability when someone has access for browsers. So where to keep it depends on the situation and you decide, but; RefreshToken will be activated when AccessToken expires on your client Login functionality.
It has become customary to set a default period of 100 days for RefreshToken. however, this time is up to you, depending on your application business preference.
I found a very clear example when I googled, you can check it below.
https://www.c-sharpcorner.com/article/jwt-authentication-with-refresh-tokens-in-net-6-0/
You can use the same functionality on your serverside code for all your clients (mobile or web not important)

User Agent + IP check for authorization (API endpoint)

Situation
I'm making an API from scratch, and security is a big problem for me when thinking about APIs (especially REST-APIs). I'm using a method similar to JWT (hashing data like 'issued_at', 'expiration_at' and user-info (email, userid) into a single hash string with salt when the login was successfull, and give it to the user, but not exactly like it), and every time a user wants to access anything beyond the login endpoint, I'm checking the provided token (hash) if it is still valid or not.
My question:
I want to check more things than the validity of the hash, because if some hackers steal someone's hash and use it before it expires, they can do things unauthorized (even when the hashes expire after 5 minutes by default). I was thinking about hashing the IP and the User-Agent string of the HTTP request along with the other details said previously when the login was successfull and I generate the hash, and checking it every time if the requesting UA+IP and the hashed UA+IP are the same. (so when someone tries to use the hash from another IP or UA, I can assume it was stolen, so I can invalidate it and request the requester to log in again). Since the hacker who stole the hash doesn't know what exact data I'm hashing, it looks like a good security door (it isn't intended to be 100% security-proof). Is it a good thing to do, or in other words, does it really adds another layer of security to the whole authorization/authentication? (of course, the main security layer stays the same, the validity of the hash itself. But would this thing make it any safer?)
Disclaimer
I know that a lot of other types and methods of authorization exists, but I don't need answers like "use xyz's method, oauth2, its safer", but answers that really give me an explanation about the dos and don'ts, strictly about the UA and IP address. I want to make my own authorization (at least the concept), to learn more about these things. Thank you in advance!

Secure strategy for staying logged-in when using OpenID

I have a website that uses OpenID to sign in users. The library I'm using, returnes a user profile when the user logges in. This profile contains user's email, name, a link to the avatar and an ID which the OpenID provider has returned.
My strategy for keeping the user logged in is this:
When the user logges in for the first time, I create a hash code based on the OpenID's returned ID
I store this hash code alongside the user's ID in 2 cookies.
When the user comes to my website, I check for these cookies, and if they're available, try to match the ID and the hash code, if it's correct, I log the user in.
Now the problem is this: if somehow this cookie information gets stolen from the user, the hacker can easily log in instead of the user himself. I could create a new hash code for each time the user logges in and update the user's cookeis but it'll make the information of other browsers/computers cookies invalid.
Since the StackOverflow website does not suffer from such problem, I would like to know what should I do to both secure my login strategy and add the functionality to stay signed in for the users.
The standard way to do this is to assign a meaningless session ID and send that as a cookie; in your database, you can store the user's credential information alongside that session ID. When a user logs out, you can invalidate that session ID.
Isn't this a problem with ALL mechanisms for letting the client stay logged in? If you log into your, say, gmail, and I steal your cookies, and put them in my own browser, there is no way to distinguish my browser from your browser and I get access to your gmail. There's no way to stop the kind of attack you're suggesting, I believe (other than the user keeping their computer free of viruses etc. that could steal the cookie)

How to securely set up cookie-based authentication in classic ASP?

What would be the most secure method of using cookies to authenticate users in a classic ASP website?
I don't want to use the ASP Session object as the session cookie times out after a while, and I'd like the user to be able to keep their login to the website active between separate browser runnings.
However, I don't want to just create a cookie containing their user ID as that could be easily forged - so what are my options here? I guess some sort of encryption but I don't really know what the standard methods of doing this is.
Your options here are pretty much limited.
Get your users to log back in again; best security approach.
This obviously applies much wider than just ASP.
The best way would be to hash the password... you should be doing this in any case where you store it in database.
The hash is a cryptographic function - when you run a string through it (eg password) you get out a long code. If the input is the same, the output is always the same.
But (this is the important bit) its mathematically virtually impossible to reverse the process - to start with the hashed value and work out the password, other than brute force (someone hashes dictionary, or random strings and looks for output that matches the hash they have).
So when the user sets up account, they put in their desired password, but you hash this, and store that. Similarly in the cookie, after they login you store the hash, not the password, and this has is compared with the hash in the db.
The downside is you can't send a password reminder since you don't know the password - to you'd have to send a password reset link and have a system to do that.
If you're really paranoid you might double hash, eg when they login the password is hashed once and stored in cookie. Its then hashed again and compared with the password in db (which is also double-hashed).
Don't Do It
Maintaining a user login quote "...between separate browser runnings" is not secure. IMHO, when you close the browser a previous login should be gone. Suppose your visitor was using a community pc at a coffee shop.
If you maintain this login the potential for the next community user to open the browser, navigate to your website and "poof" they are automatically logged in as the previous user.

What information to save to a cookie for future account authentication?

So I'm building my first ever website with user accounts. What data should I store to the cookie so the user can prove that they are in fact that user? Right now when the user logs in I save the user ID, the username, a randomly generated session ID and the hashed and salted password for future authentication. I'm not sure if I should be doing the last part...
Before anyone suggests it I would use OpenID but my target audience isn't guaranteed to be tech-savvy and I think it would just confuse them. I don't want interested users going to the competition so I'm keeping things as "regular" as possible. I suppose I could offer both site registration AND OpenID...
You really only need to store the session ID: as long as the session data is kept, any other data can be stored server-side against the session. Keeping personal data in cookies isn't a good idea, since they are stored and transmitted in plaintext.
Have a look into session hijacking if you are worried about people grabbing onto someone else's session using this method... Though, with cookies it's usually a little harder to do (the most common case of this happening is on sites that pass the session ID around as part of the GET request).