Is it bad practise to automatically use the refresh token in an interval? - authentication

As I am working on implementing a proper auth flow into a react web app, I am presented with different patterns of how to use access and refresh tokens.
I am considering the following two patterns:
Creating some sort of middleware to the fetch API:
This middleware runs before every request to the backend and checks whether the access token is still valid or not.
If it is invalid, it first calls the auth server to fetch a new access (and refresh) token.
Creating an interval which is independent from all other logic to keep the access token alive.
Say if the access token is valid for 5 minutes, the interval will run every 5 minutes to fetch a new access token
I would also make sure it only runs every five minutes, if the user is still active , so that the application left open without any user interaction for a long time will automatically log out
Any API call simply uses the currently active access token and does not need to worry about checking the token first or anything
The second approach seems much much easier and cleaner to implement for me, since it does not add any complexity to fetching data and is completely independent/seperate to the app otherwise.
I've been having a hard time to research this question though tbh. I'm not sure if there is some security issue I'm missing with that approach.
So my questions are:
Is there any security issue with fetching a new access token in an interval from the clients side?
Is there a common practise on how SPA apps (like the react app I mentioned) handle access tokens?
If yes, what is that common practise?
If there is no security issue, are there other cons of the second approach that I am missing out on?
Thank you for your answers in advance!

I think the answer depends, if you always do it every X minutes, and you have many active clients, it might create more load on the backend, compared do doing it on a need basis. Perhaps all clients are not so active all the time?
One thing to look out for is to make sure you don't trigger multiple requests at the same time to request new refresh tokens. If you get a race condition here, then you might be logged out (if you use one-time refresh tokens)
Also it is worth considering to use the BFF pattern, do watch this video
Using the BFF pattern to secure SPA and Blazor Applications - Dominick Baier - NDC Oslo 2021

Related

How to create a permanent authentication token with Auth0?

I need to create a permanent identifying URL for each user, through which (by visiting it), they will be logged in.
For example:
User1: https://www.example.com/?userToken=gj56u45g64g56uy54g6uyg546
User2: https://www.example.com/?userToken=8o9k7ok9o89k7o9ko8k9o78k9
The functionality is similar how one would identify to an API, or click an email confirmation link, but it has to be permanent or at least with a very long duration, because it will be stored on an NFC chip.
How can I do this within Auth0? (or Oauth 2, because I think that's what they use?)
From some reading that I did, I did not seem to find a way to get a permanent token for a user, and those tokens that I could get, had a maximum life cycle of 24 hours, which is too short for the intended use.
I have done this fairly quickly in a custom way, but within Auth0 I am not sure how it's done.
I read about refresh tokens, but these it seems to me, will need to be written to the NFC chip every time, which I can't do.
When you authenticate, you are given an ID and access token.
You typically use the ID-token to create a long-lived session-cookie, that can live as long as you like. The ID-token is by design a pretty short-lived token, by default like 5 minutes in some systems.
If it is for an embedded system, then there also the device-flow, that is more suitable for devices with a limited UI https://auth0.com/device-flow
I doubt writing JWT tokens from an authorization service is the right approach, as you have to remember that these services typically change/rotate their signing keys, so tokens issued for 6 months ago, might not be accepted today. And for example in a compromise and they are forced to change all their signing-keys, then all your devices will be made useless.
Better approach is to write your own "key" into each device.

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)

Auth0: Specific questions about token storage and flow for mobile app

I’m building a react native app that will interact with APIs that I also write/manage. I have found Auth0 documentation for implementing this flow, but I’m not sure on where/when to save the tokens. I want to be sure I nail this step, because I feel like it has the potential to reduce the security of the flow by a great deal if I don’t do it correctly.
Here is the flow as I understand it (no error handling, only happy-path for sake of brevity):
A user enters the app for the first time, or is not already logged in
They log in using the Auth0 web-login-thingy
I receive a token
I can use the token to authenticate with my API
Questions:
Do I store that token? I don’t want my users to have to log in every time they use the app. If I do store the token, where do I store it?
If I’m not storing it, what do I do? Do I ping an authentication/authorization endpoint with Auth0 every time they open the app and get a new token?
Say I am storing the tokens, if I'm using the ID token for user data, should I be hitting the API again regularly to keep it up to date? Only when the user opens the app again? Not until they trigger a change in the app?
Instead of using the ID token for user data, should I just use that to get the user's ID and ping my database for user data?
I have the basics of this flow, and I'm able to sandbox it, but I want to start applying production-ready app logic to this flow and that's where I'm stuck. I’m a little lost here, so any help is good help.
Thanks!!
Here's a brief answer to your questions when using Auth0:
Yes! you store it, the most secure way to store the token is in your device's local storage, that way it is not kept either in application's state or in a global variable.
2&3. See above, but to add more information, you can configure your tokens to have an expiry length. in theory you would convert this 'expiry time from inception' to a date object, and can do one of two things; you can request a new token using the Refresh Token (that comes with the original) once the expiry has been reached, or force the user to re-log in and re issue a new token at this time (i prefer the latter, prevents people from just renewing their tokens forever as long as they remain logged in)
Use the auth token to request user information after login, this can be stored in app state/global variables/wherever. You then want to use the auth token in the Authorization Header for each API call, along with whatever data you are sending. this ensures that even once someone is INSIDE the application, they need to have a valid token to actually do anything involving data (imagine someone back-dooring into your app and skipping the authorization, or using something like postman to just hammer your API with garbage). it would work something like this: GET userData { Header: auth token } -> GET userProfile (by sending your user ID returned from GET userData) PLUS {Header: auth token }
I can give more in depth examples if you wish, and i apologize if i misunderstood any of the question and gave redundant/incorrect answers
Edit: Resources about using secure storage for keys
Document for when to use in-memory storage Vs persistent storage. The TL;DR is use in-memory if the key is expected to expire before a standard session duration, and persistent for storing a key between sessions
https://hackernoon.com/mobile-api-security-techniques-682a5da4fe10
link to Keychain Services doc
https://developer.apple.com/documentation/security/keychain_services#//apple_ref/doc/uid/TP30000897-CH203-TP1
link to SharedPreferences doc
https://developer.android.com/reference/android/content/SharedPreferences.html
AsyncStorage is a simple, unencrypted, asynchronous, persistent,
key-value storage system that is global to the app. [1]
You could store it in your AsyncStorage, but thats not necessarily a secure location itself (e.g. not encrypted, accessible on rooted devices...). Typically clients will issue access tokens that last anywhere from several hours to a couple days and these will provide their owner access to your API-resources. If there is sensitive data behind your login screen, you're probably better off simply re-doing the auth-flow and invalidate older access tokens on login.

User registration/authentication flow on a REST API

I know this is not the first time the topic is treated in StackOverflow, however, I have some questions I couldn't find an answer to or other questions have opposed answers.
I am doing a rather simple REST API (Silex-PHP) to be consumed initially by just one SPA (backbone app). I don't want to comment all the several authentication methods in this question as that topic is already fully covered on SO. I'll basically create a token for each user, and this token will be attached in every request that requires authentication by the SPA. All the SPA-Server transactions will run under HTTPS. For now, my decision is that the token doesn't expire. Tokens that expire/tokens per session are not complying with the statelessness of REST, right? I understand there's a lot of room for security improvement but that's my scope for now.
I have a model for Tokens, and thus a table in the database for tokens with a FK to user_id. By this I mean the token is not part of my user model.
REGISTER
I have a POST /users (requires no authentication) that creates a user in the database and returns the new user. This complies with the one request one resource rule. However, this brings me certain doubts:
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
If I decided to return the token together with the user, then I believe POST /users would be confusing for the API consumer, and then something like POST /auth/register appears. Once more, I dislike this idea because involves a verb. I really like the simplicity offered in this answer. But then again, I'd need to do two requests together, a POST /users and a POST /tokens. How wrong is it to do two requests together and also, how would I exactly send the relevant information for the token to be attached to a certain user if both requests are sent together?
For now my flow works like follows:
1. Register form makes a POST /users request
2. Server creates a new user and a new token, returns both in the response (break REST rule)
3. Client now attaches token to every Request that needs Authorization
The token never expires, preserving REST statelessness.
EMAIL VALIDATION
Most of the current webapps require email validation without breaking the UX for the users, i.e the users can immediately use the webapp after registering. On the other side, if I return the token with the register request as suggested above, users will immediately have access to every resource without validating emails.
Normally I'd go for the following workflow:
1. Register form sends POST /users request.
2. Server creates a new user with validated_email set to false and stores an email_validation_token. Additionally, the server sends an email generating an URL that contains the email_validation_token.
3. The user clicks on the URL that makes a request: For example POST /users/email_validation/{email_validation_token}
4. Server validates email, sets validated_email to true, generates a token and returns it in the response, redirecting the user to his home page at the same time.
This looks overcomplicated and totally ruins the UX. How'd you go about it?
LOGIN
This is quite simple, for now I am doing it this way so please correct me if wrong:
1. User fills a log in form which makes a request to POST /login sending Basic Auth credentials.
2. Server checks Basic Auth credentials and returns token for the given user.
3. Web app attached the given token to every future request.
login is a verb and thus breaks a REST rule, everyone seems to agree on doing it this way though.
LOGOUT
Why does everyone seem to need a /auth/logout endpoint? From my point of view clicking on "logout" in the web app should basically remove the token from the application and not send it in further requests. The server plays no role in this.
As it is possible that the token is kept in localStorage to prevent losing the token on a possible page refresh, logout would also imply removing the token from the localStorage. But still, this doesn't affect the server. I understand people who need to have a POST /logout are basically working with session tokens, which again break the statelessness of REST.
REMEMBER ME
I understand the remember me basically refers to saving the returned token to the localStorage or not in my case. Is this right?
If you'd recommend any further reading on this topic I'd very much appreciate it. Thanks!
REGISTER
Tokens that expire/tokens per session are not complying with the statelessness of REST, right?
No, there's nothing wrong with that. Many HTTP authentication schemes do have expiring tokens. OAuth2 is super popular for REST services, and many OAuth2 implementations force the client to refresh the access token from time to time.
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
Typically, if you create a new resource following REST best practices, you don't return something in response to a POST like this. Doing this would make the call more RPC-like, so I would agree with you here... it's not perfectly RESTful. I'll offer two solutions to this:
Ignore this, break the best practices. Maybe it's for the best in this case, and making exceptions if they make a lot more sense is sometimes the best thing to do (after careful consideration).
If you want be more RESTful, I'll offer an alternative.
Lets assume you want to use OAuth2 (not a bad idea!). The OAuth2 API is not really RESTful for a number of reasons. I'm my mind it is still better to use a well-defined authentication API, over rolling your own for the sake of being RESTful.
That still leaves you with the problem of creating a user on your API, and in response to this (POST) call, returning a secret which can be used as an access/refresh token.
My alternative is as follows:
You don't need to have a user in order to start a session.
What you can do instead is start the session before you create the user. This guarantees that for any future call, you know you are talking to the same client.
If you start your OAuth2 process and receive your access/refresh token, you can simply do an authenticated POST request on /users. What this means is that your system needs to be aware of 2 types of authenticated users:
Users that logged in with a username/password (`grant_type = passsword1).
Users that logged in 'anonymously' and intend to create a user after the fact. (grant_type = client_credentials).
Once the user is created, you can assign your previously anonymous session with the newly created user entity, thus you don't need to do any access/refresh token exchanges after creation.
EMAIL VALIDATION
Both your suggestions to either:
Prevent the user from using the application until email validation is completed.
Allow the user to use the application immediately
Are done by applications. Which one is more appropriate really depends on your application and what's best for you. Is there any risk associated with a user starting to use an account with an email they don't own? If no, then maybe it's fine to allow the user in right away.
Here's an example where you don't want to do this: Say if the email address is used by other members of your system to add a user as a friend, the email address is a type of identity. If you don't force users to validate their emails, it means I can act on behalf of someone with a different email address. This is similar to being able to receive invitations, etc. Is this an attack vector? Then you might want to consider blocking the user from using the application until the email is validated.
You might also consider only blocking certain features in your application for which the email address might be sensitive. In the previous example, you could prevent people from seeing invitations from other users until the email is validated.
There's no right answer here, it just depends on how you intend to use the email address.
LOGIN
Please just use OAuth2. The flow you describe is already fairly close to how OAuth2 works. Take it one step further an actually use OAuth2. It's pretty great and once you get over the initial hurdle of understanding the protocol, you'll find that it's easier than you thought and fairly straightforward to just implement the bits you specifically need for your API.
Most of the PHP OAuth2 server implementations are not great. They do too much and are somewhat hard to integrate with. Rolling your own is not that hard and you're already fairly close to building something similar.
LOGOUT
The two reasons you might want a logout endpoint are:
If you use cookie/session based authentication and want to tell the server to forget the session. It sounds like this is not an issue for you.
If you want to tell the server to expire the access/refresh token earlier. Yes, you can just remove them from localstorage, and that might be good enough. Forcing to expire them server-side might give you that little extra confidence. What if someone was able to MITM your browser and now has access to your tokens? I might want to quickly logout and expire all existing tokens. It's an edge case, and I personally have never done this, but that could be a reason why you would want it.
REMEMBER ME
Yea, implementing "remember me" with local storage sounds like a good idea.
I originally took the /LOGON and /LOGOUT approach. I'm starting to explore /PRESENCE. It seems it would help me combine both knowing someone's status and authentication.
0 = Offline
1 = Available
2 = Busy
Going from Offline to anything else should include initial validation (aka require username/password). You could use PATCH or PUT for this (depending how you see it).
You are right, SESSION is not allowed in REST, hence there is no need to login or logout in REST service and /login, /logout are not nouns.
For authentication you could use
Basic authentication over SSL
Digest authentication
OAuth 2
HMAC, etc.
I prefer to use PUBLIC KEY and PRIVATE KEY [HMAC]
Private key will never be transmitted over web and I don't care about public key. The public key will be used to make the user specific actions [Who is holding the api key]
Private key will be know by client app and the server. The private key will be used to create signature. You generate a signature token using private key and add the key into the header. The server will also generate the signature and validate the request for handshake.
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
Now how you will get private key? you have to do it manually like you put facebook, twitter or google api key on you app.
However, in some case you can also return [not recommended] the key only for once like Amazon S3 does. They provide "AWS secret access key" at the registration response.

Where to store authentication token in RESTful API

I have started to design a RESTful API and I'm thinking about how to handle authentication. I want to use some kind of authentication token but I can't use OAuth o similar infrastructures so I have to handle it myself.
One of the requirements for this API is that it must have good performance, enough to handle a high volume of requests before there is the need to scale; my concern is how to make on each request the time needed to verify the token (integrity, expiration, IP Address, etc...) as little as possibile.
I suppose the token should some kind of hash and not an encrypted string containing the user information because the decryption time would be to heavy.
I've read that I could store the tokens in an in-memory hashtable where the key is the token and the value is the user info needed to process the request, but how can I make this work in a clustered environment where there will be an hashtable on each "node"?
Should I put tokens on a DB table an hit the DB every time also Handling manually the retention of expired tickets?
Probably it's not that important for the question but I'm using Spring MVC for the RESTfull API.
Thanks in advance.
I solved my problem by using both an in-memory cache and a db cache. Here is a summary of my solution that may help anyone with the same task.
the user logs in and in that moment a unique key is generated and sent back to the user.
that login token (which is basically a GUID with some processing) is also store in a db table with additional info like exipiration and with the user's info and roles. the same pieces of information are also store in memory (google guava hashtable where the token is the key)
the token must be passed along with every api call in the authorization token as #ipa suggested
the server code checks if the token is in its memory cache the user info are already available otherwise (e.g. the api call is done on another node in the cluster) the token is search in the token db
once the token is found you can check expiration, roles, etc...
This grants a good level of performance and security, the token can be generated with any arbitrary algorithm even a relative slow one since you don't have to recalculate it on every api call. Also this works with a stateless service wich can be scaled up horizontally.
I assume you use https and therefore all the traffic is encrypted. I'd suggest one of the following principles.
Basic Authentication
You can add the credentials in the Authorization header of the request. This credentials are encoded with Base64 (see below). This credentials could be sent on every request and then checked with your DB. To get this faster and less IO intensive you can still use a cache. Once I implemented an API like this without a cache and was able to handle thousands of requests per second.
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Authorization Token
There are different ways to implement your idea with a token. A common one is that every API user has his own token usually called api key which never expires. Another one is that you first have to authorize (Basic Authentication) and then get a token back which expires. This one is then used as api key for a certain time.
Either way you have to decide whether to use a cache or not. I would keep it simple and go for basic authentication and check the db every time. Almost every framework has very good support for this approach because it's simple http. If this causes performance issues (I'd recommend performance tests anyway) try to add the table with your credentials to the JPA cache. If you want to implement something with expiring tokens have a look at Infinispan.
You can store token in Redis. If you are going to store it in DB, make sure you optimise server (if you are managing it) for read operations. I have couple of implementation where folks have used key value store as well. Hashtable is also good idea.