JsonWebToken: activity-based expiration vs issuing time-based expiration - security

I'm fairly new to token based authorization. I'm trying to find the flaws in a custom expiration/token-refresh scheme.
I have a basic JWT auth setup in an Express API; I'm setting the JWT expiration to 1 hr; However, JWT checks token expiration relative to the time the token was issued. I would prefer that the expiration time gets reset after each successful api call. If my user is actively using the app for more than an hour, I don't want them to have to log back in to refresh the token (and possibly lose whatever data they are working on.)
On the the other hand, I do want the token to expire if they are not responsive for more than an hour.
I have come up with the following approach:
During every successful API request, issue a new JWT and send it in a
custom response header. My client side code is responsible for
checking this JWT response header and using its value as the new default Authorization request header. Thus, if there is no API
request from the user for more than 1 hour, the token will expire and
not be refreshed. Login would then be required. In addition, the original issue-date of the token (timestamp of login-authentication) will be stored so that a "hard-expiration" of the token will be enforced after 24 hours.
This seems fairly straightforward and reasonably secure, but I haven't seen any reference to it in my JWT research. Is there a better way to achieve the same goal? Am I missing a major security hole with this approach?
UPDATE:
After thinking of this for some time, I realized that the problem with this is that it opens the door to replay attacks that could not be thwarted by token expiration. So there should absolutely be a "hard-expiration" check: hard expiration would invalidate the token at some time after issue date, regardless of recent user activity.

Here you can check my answer for this scenario:
implementing refresh-tokens with angular and express-jwt
What I have done is to have a time window where the server checks if the token expiration and the local server time is in this window and then send a response header with the refreshed token.

If you agree and realize that you need a hard expiry time anyhow, why not set the expiry time of the (one and only) access token to that and stick to plain OAuth 2.0? An asymptote of what you're doing now, would be to issue your own API specific token/cookie after first use of the access token (in the API response) and enforce subsequent API access based on that. That is a valid approach, but duplicates a lot of stock OAuth 2.0 Authorization Server functionality in your own API. I don't see a good reason to go there.

Related

Access/Refresh token confusion

I've been doing a lot of reading on this subject and I can see that there are many different opinions and approaches to authenticating using JWT.
My understanding is as follows:
In its simplest form, a JWT authentication mechanism should:
Verify username and password.
Create a signed JWT access token containing information (depending on the app's needs) on the user.
Send that token in the response.
The client then stores the token (which from my understanding there is some debate whether a secure cookie or localStorage is more secure), and sends it with each request's headers.
The server can then authorize the user using middleware verifying the JWT. No state, all information in contained within the JWT.
Assuming the JWT has no expiration (or perhaps a very long expiration date, maybe a couple of months), it sounds good because I can provide the user a persistent logged in state for a long time. The concern is, to my understanding, if the JWT was to be stolen, it is essentially an unlimited access card and a huge security breach.
So that's where the refresh token enters, the server issues both refresh and access tokens (refresh token with a long/unlimited expiration and the access token short).
The server database holds some kind of table of valid refresh tokens (so that if one is stolen it can be invalidated easily) and when issuing a new access token, validates the refresh token.
This also adds the need to add some sort of countdown mechanism on the front end where a refresh request is to be sent to the server prior to the access token expiration date so that the user won't be logged out.
And my question:
Why? If we go through all the trouble of creating a db table for refresh tokens, why not just make a table of valid access tokens and invalidate them if needed? How is that less secure than using refresh tokens?
Thank you
Access tokens aren't primarily used to provide extra security, but to provide efficiency and decoupling.
An access token can have a very short lifetime - maybe even less than a minute - but be used to authenticate multiple requests to different services within that time. Those services don't need to have any access to the authentication database, because they can trust the access token until its expiry date; that makes them faster and simpler.
For instance, if you're using a dynamic page with lots of AJAX requests, that might run in very quick succession. Those AJAX calls might be implemented as serverless functions (e.g. AWS Lambda), or as standalone scripts in different programming languages on different servers, or you might just want to make them as efficient as possible, and avoid any database access. The only information that needs to be shared between them is a public key to verify the signature on the JWTs they receive.
From a security a point of view, this is a trade-off: on the one hand, an access token for a user whose access has been revoked can still be used until it expires; on the other hand, the long-lived refresh token is transmitted much less than a traditional session token, so there are fewer chances for it to be intercepted.
To address your concrete concern:
This also adds the need to add some sort of countdown mechanism on the front end where a refresh request is to be sent to the server prior to the access token expiration date so that the user won't be logged out.
No "countdown" is needed. The code that has access to both tokens simply looks at its current access token before using it; if it has expired, or is about to expire, it requests a new one using the refresh token. It then gets a new access token, and probably a renewed refresh token - the expiry date on the refresh token represents how long the user can be idle before they are automatically logged out.
We don't need to make a table of access tokens and it is dangerous to secure.
We have to save only refresh token and add one field for valid/invalid in the table. And send access token and refresh token to the client side.
The clients send access token with each request's headers.
The server can authorize the user using middleware verifying the JWT.
After some time, the access token will be expired(access token's expired time is shorter than the refresh token's expired time).
The client sends refresh token to server.
Then the client will get new access token using refresh token(refresh token should be recreated, in other words, we can use only one-time refresh token, we have to update table of refresh token with new refresh token).
The client can get new access token and refresh token.
I hope it will be help you.

Can i use a Firebase token (JWT) to identify a user with an expire date > than 1 hour?

I'm using Cloud Firestore for Firebase to store informations about a Rest API Service written in NodeJs.
So, every request to Node will ask to Firebase informations about the service and, for first, it will authorize the request.
I thought that use an user generated JWT will be the best solution because the client have to simply include the JWT in his requests to authorize itself.
A Firebase JWT is related to the uid of the user that generates it.
Obviously, there'll be a control panel where the user can log in with email/pw and generate the JWT, and then the JWT will be included in his client system, for example like simple APIs that requires an API Key to identify the user and to work.
So, the idea appears to work good but i noticed that the Firebase JWTs expire in only 1 hour!
The user have to log-in to the control panel every hour to re-generate the JWT. That's not so friendly.
How can avoid this problem? How can i make the JWT expires in more than only 1 hour?
According to documentation:
The maximum lifetime of a token is 24 hours + skew.
[...]
with a skew of up to 10 minutes.
That means you cannot use these tokens forever, which kind of makes sense.
I looked at custom tokens and found:
The time, in seconds since the UNIX epoch, at which the token expires. It can be a maximum of 3600 seconds later than the iat.
Note: this only controls the time when the custom token itself expires. But once you sign a user in using signInWithCustomToken(), they will remain signed in into the device until their session is invalidated or the user signs out.
Perhaps you can do something with the signInWithCustomToken() as once logged in it expires only when the user is invalidated or signs out, but I believe the best course of action would be to look for another approach.

A few questions about json web tokens

I have recently started using json web tokens and I have a few unanswered questions
what would happen if a users token expires while they are online? would they be forced to log in again when they request the next protected route? and if so it feels like there has to be a way around this so that the user does not randomly get logged out
how would you log someone out before the jwts expiration date considering the client holds all the info
any clarification on those 2 questions would be appreciated
what would happen if a users token expires while they are online? would they be forced to log in again when they request the next protected route? and if so it feels like there has to be a way around this so that the user does not randomly get logged out
When you make a request in a webapp, you need to pull in the available token. So the answer is "what does your app do?". There are lots of things you can do, such as making the request with the invalid token, or no token at all. But obviously that's not really a good idea. The best strategy is to:
Before every API call needing a token, check if the current token is valid
If the token isn't valid ask your auth provider to get a new token. This is known as silent authentication. How the provider handles this is totally up to them, usually they have a HttpOnly cookie saved for a secure domain, and return a new JWT.
If the silent auth fails, then the provider will tell you to log the user in.
At this point the best course of action is to redirect to the user to the auth provider using the same "login strategy" they previously used, to get a new "session" and a new "token".
how would you log someone out before the jwts expiration date considering the client holds all the info
Logging out is completely separate from token expiration. Logging out from a user standpoint is:
Tell the auth provider to remove the HttpOnly secure cookie
Delete the JWT in the browser
Change the UI to display the user as no longer logged in.
But that doesn't expire the token. The token will always be valid until the exp date. If you want to also prevent that token being used as if it was valid, you must deny-list the token using your AuthZ IAM as a service. For instance, if you were using Authress to manage access control, a DELETE https://api.authress.io/v1/users/{userId}/tokens/{tokenId} would cause subsequent checks using that token to return Forbidden. However, I will stress, the token is still valid, but you've taken the step to mark it as Deny-listed.
would they be forced to log in again when they request the next protected route?
If there is no other information that associates the session with the logged-in user (for example, there aren't any cookies or other tokens the server can use), yes.
Yeah, it's not very user-friendly, and JWTs often have a short expiry time. A common solution to this issue is to provide a refresh token as well, which could be stored in a HttpOnly cookie:
A refresh token has 2 properties:
It can be used to make an API call (say, /refresh_token) to fetch a new JWT token before the previous JWT expires.
It can be safely persisted across sessions on the client!
This way, the client can always have a valid JWT at any one time; they won't have to log back in, or logout and then log back in.
how would you log someone out before the jwts expiration date considering the client holds all the info
You can implement logic on the server to somehow blacklist or ignore the JWT from a particular user until they log in again. For example, after parsing the JWT, you could check to see whether the server considers the token to still be usable or not. If not, return a 401 error.

Logout/invalidate a JWT

I'm using custom authentication in Azure Mobile Services by generating a JWT (JSON Web Token) in a custom login API. Once a user has a JWT, it's valid until its encoded expiry time is reached.
Beyond explicitly checking the JWT token against a sessions table on every authenticated request, is there a way to invalidate the JWT token before its expiry time (as would happen when a user logs out) such that any subsequent request made with that token as a value in the X-ZUMO-AUTH header would never reach any table API or custom API scripts?
Not really. When a user logs out in the client the JWT it uses isn't really invalidated - it's just removed from the client's memory (see the code on the managed SDK, for example). The JWT validation is done by checking the its signature against the mobile service's master key, and unless this key is changed (which would invalidate all of your service's JWT tokens, which I don't think is what you want), the token will be valid until it's expired.
Since you're generating the JWTs yourself you can consider using a smaller expiration time which may help in your case.
You can also suggest this feature in the mobile service's feedback forum. There's one related feature suggestion which I created, you can also consider adding a comment to that and voting it up.
To support JWT invalidation (there are always reasons):
I ended up storing a unique string per user which I hash with a global common string, so I can invalidate a single user's token, or all tokens as required.
No. The only way to logout a user and invalidate a JWT token is to remove/delete it out of the session table. This is the way you are already doing.
Store the token in a blacklist database table/collection, along with its expiry date.
Load unexpired blacklisted tokens into memory (indexed) and check every request's token against it.
Set an interval to reload the blacklist intermittently (to remove expired tokens from memory).

OAuth2 and Google API: access token expiration time?

We have a standalone Java application (see "Installed application") which runs periodically and uses Google API (updates some information from customer databases/ldap/...).
To access Google APIs we store username and password in configuration file, which is a security risk and customer does not like that. So we would like to use OAuth2 long-living access token instead.
What`s default expiration time for Google OAuth2 access tokens ?
As we will have only access token in application, app itself cannot refresh it when access token expires.
Personally I think that OAuth2 implementation in this case will not bring any major benefit but let`s focus on main question - default expiration times.
You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.
However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).
EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:
It is a parameter in the response (expires_in)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.
There is also an API that returns the remaining lifetime of the access_token:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}
This will return a json array that will contain an expires_in parameter, which is the number of seconds left in the lifetime of the token.
The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

Resources