How to handle JWT expiration - jwt

I have a question on "make the browser send out a request to exchange for a new token at the sixth day. Accordingly, on the server side, create a restful API named /token/extend which will return a new token if given a valid token."
Let's assume that I implement this concept. When token is about to expire, we will generate new valid token if old valid token is provided.
Now, let's assume, Hacker gets the token. He uses this token to communicate with APIs. Hacker communicates for 6 days. On 6th day, our "/token/extend" API will generate new token for him so he can communicate for another 6 days, and probably forever. Will this situation occur? or Am I missing something here?

The general way you would force your users to obtain a new token after 6 days would be by simply setting the exp field (expiry) in the claims of the JWT to expire after 6 days. The exact mechanism by which users would use to obtain a new token depends on your implementation.
The most basic implementation would be to just let the incoming request on the sixth day to fail, forcing the consumer of the API to redirect to the login page. From there, the user would have to login again to obtain a new valid JWT. A more elaborate method would use refresh tokens. With this approach, when the user first logs in, he would receive an authentication token with a 6 day expiry (as before), but would also receive a refresh token which would expire a little bit later. On the sixth day, when the user tries to access a service, the request would again fail. However, in this case, the consumer (e.g. a website or mobile app) could take the refresh token and request a new access token under the hood. This would be a more seamless way of handling the mandatory 6 day expiry. Note that with the refresh token approach, the user might never know about the 6 day expiry.
Regarding your concerns about hackers obtaining other people's tokens, you should mostly just forget about this. If someone stole your wallet, there is all sort of havoc he could do to you, e.g. using your credit cards, stealing your identity, etc. The same could happen with a stolen/sniffed JWT. The best practice here is to just make sure you are using two-way SSL for all communication, and also encourage your users not to use your services in places like Internet cafes.

Related

If JWT-Token is stolen

For instance, if an attacker gets ahold of your JWT token , they could start sending requests to the server identifying themselves as you and do things like make service changes, user account updates, etc. Once an attacker has your JWT it is game over.
So how we can secure our routes with JWT token if token is stolen ?
Basically you're right, if an attacker steals an access token (it doesn't have to be a JWT), then she can do anything that that token allows, and for as long as the token is valid. There are some steps you can take to mitigate the problem or do some damage control:
Keep short expiration times of tokens. If the token lives for only 2 or 5 minutes then the amount of data an attacker can steal will be limited.
Limit scopes of tokens. You shouldn't have tokens with which you can do everything. If you issue tokens which allow the user only to read their data, then even if someone steals it, they won't be able to change the password.
Use proof-of-possession tokens. These are tokens which are tied to the client which received them in the first place. When someone steals such a token, they won't be able to access the API, unless they also have access to a proof of possession (which can be a certificate). These are examples of POP tokens: Certificate-bound access tokens and DPoP tokens
You can use something which at Curity we called a Token Handler pattern to hide your tokens from the browser and fallback to good old sessions. This makes your tokens much harder to be stolen.
If you're working with JWTs, have a look also at an article I wrote about security best practices when handling JWTs.

How to prevent log out users when changing JWT secret?

I am using a JWT token implementation of this https://jwt-auth.readthedocs.io/en/develop/quick-start/
I need to update the secret key and is there a way to update it without logging out every user? I presume it's not possible to reuse the old token once my secret key is changed. So all my users will be logged off and need to log in again. Is there any way to go around this?
If not, if for security reason, I need to update the secret monthly, that will be pretty troublesome to ask my user to re-login monthly.
Thanks!
If you change your keys it's correct to invalidate all the tokens signed with the old ones as they are to be considered expired.
It's a good practice to let the token expire as well after a certain amount of time. Usually you implement a mechanism based on two tokens, access_token with an expiration of 1h (usually) and a refresh_token with a longer expiration (usually 24h). The second one is used to renew the first one. When the second one expires, the user has to be considered logged out.
What you need is to implement a refresh token mechanism. You can implement it from scratch, for learning purposes, or you could just implement OAuth 2.0 protocol, since it's a flow that it already supports. There are lots of libraries both for server side and client side implementations
https://oauth.net/

JWT authntication and its alternatives to reach RESTfulness of web application back-end

In my company, we are building a web application and most actual problem is to pick an authentication solution. Im thinking about 3 of most used way to maintain
session with authenticated user: stateless JWT (all session data holds JWT token in its payload), stateful JWT (token is only used to validate requests and in its payload it has session ID to session data record at server) and traditional session ID stored in cookie, which requires additional check for matching id in server.
Because i want to build this app RESTful, only first way seems right to me. This way a server does not need to hold any state.
My first question is: Is it ok, to store all session data in token payload (of course, those data are not that big and they are not supposed to be a secret, hence no security is needed).
Also, im going to implement logout logic as well and i know, that blacklisting tokens, which is in my case, i think, best solution ruines statelessness too.
Do you know of any other way to implement logout logic which IMMEDIATELY invalidates JWT token ?
Thank you for your answers.
EDIT:
In case of invalidation, im thinking about sending an updated token with either a flag which tells "im invalidated token" or with expired expire date. This solution but works only for "good boy" users. Hackers will keep previous and still valid token.
Logout with JWT works by deleting the token client-side. Like this.
function removeToken() {
localStorage.removeItem("jwt-token");
}
Without the token, the user is logged out. So I think it is immediate?

Is "logout" useless on a REST API?

Considering that, by definition, a REST API is stateless: is the "logout" operation useless?
I mean, I'm creating a REST API using encrypted JWT. Each token has an expiration time of, let's say, 60 minutes. If I save on a database table the last tokens generated by the API, the "logout" would be done deleting them from the table of valid tokens. But, if I do that, I understand that the API will cease to be stateless, right?
So, I understand that I shouldn't do that. The only solution that I'm thinking is make the JWT expiration time shorter, to 5 minutes, don't implement a "logout" operation and just let the tokens expire.
Is this the correct approach?
I mean, I'm creating a REST API using encrypted JWT
The JSON Web Token (JWT) tokens encodes all the data about the grant into the token itself. The most important advantage of this approach is that you do not need a backend store for token storage at all. One disadvantage is that you can't easily revoke an access token, so they normally are granted with short expiry and the revocation is handled at the refresh token. Another disadvantage is that the tokens can get quite large if you are storing a lot of user credential information in them. So if:
If I save on a database table the last tokens generated by the API,
the "logout" would be done deleting them from the table of valid
tokens
Then you would lose the most important advantage of using JWT and also, still have all those disadvantages, which seems unreasonable to me.
So, I understand that I shouldn't do that. The only solution that I'm
thinking is make the JWT expiration time shorter, to 5 minutes, don't
implement a "logout" operation and just let the tokens expire.
Is this the correct approach?
In my opinion, if you're planning to use JWT, YES! it's better to rely on the token expiration. For more details on this approach you can check this question out.
Is “logout” useless on a REST API?
Regardless of the fact that you're using JWT and similar to any other decent questions on computer science, the answer would be It Depends. The most important advantage of Statelessness is that your API would be more scalable. If you choose this path, probably, every request on your API should be authenticated, since you may need to search a backend store for the given token or decode a JWT token. So, in this case you may have some performance cost on a single node but in a big picture, you would still have the scalability. I guess what i'm trying to say is, if you do not need that scalability, you're better off to choose a Stateful approach. Otherwise, pure REST principles is the way to go.
Automatic token expiry is a separate concern from an explicit "log out" mechanism and, as such, they are both perfectly valid actions regardless of whether your API is ReSTful or not.
When a user logs out they are making a conscious decision to invalidate their access token - for example, if they're using a public computer or borrowing someone else's device temporarily.
Automated expiry is used to ensure that the user must revalidate, in some fashion, on a regular basis. This is good for server-side security.
Access tokens are not about sharing session state between client and server - it's entirely possible to implement an access token system without shared state and the token itself doesn't implement session state, it's only used to verify that the user is who they claim to be. As such, access tokens are not really anything to do with the statefulness of the API.
I think it depends on the behavior that you want for your application, and how secure you need it to be. Do you really need to invalidate the token?
For instance, you could just remove your token from your frontend (browser or app). In theory, it is the only place that stores that particular token. If the token is compromised, it will still be valid until it expires, though.
If you really need to invalidate it server side, a common approach would be to create a blacklist with the token, and clear the expired entries from time to time.
But what if you need your application to accept just one token for each user, like in a bank app that you can only be logged in one device at time? For that purpose the blacklist won't do the job, so you will need to store a single token for each user and check if the passed token is the same. At logout, you would just clear that unique entry. Or you may just use sessions.
So, it is not useless, It just depends on your application.
I would argue that your API is already stateful just by the sheer fact that you have a token around. I also wouldn't get too hung up on REST purity, meaning that everything has to be stateless come hell or high water.
Put simply, if your application requires login, then you need a way to logout. You can't implement a short expiry because that's just going to be a really annoying experience to consumers of the API. And you can't just have no logout at all, because thats a potential security flaw.
I have a similar REST API that I support and I implemented a logout endpoint that is a DELETE call. It simply deletes the token information on the server side and clears any type of authentication for the logged in user.
TL;DR
No, a logout is not useless in a REST API. In fact, for APIs that require authentication, it is more or less a necessity.
With a short expiration time on the token I would think for most applications deleting the token from the client on logout would be a good solution. Anything more would rely on the server and no longer be stateless.
The good solution here would be to delete the token from the user.
So typically when you log in, you will get back a token from the server and store it in localStorage or sessionStorage (depending on the user wanting to be logged in after closing the tab) in the browser, and then send the token from there in the headers with any request that you make to your api.
Then if the user logs out, you don't even contact the api (you don't make any requests to your server), you just clear the sessionStorage or localStorage, use the command localStorage.clear() or sessionStorage.clear() , and then if the user will want to send more requests, he'll have to login again in order to get another token.
One drawback to this approach is, that if a virus, for example gets the token from the local or session Storage before the user logs out then, it will still be able to send requests as you, as the token will still be valid.
One solution to that would be to create a token blacklist in the database, and store the token there if the user logs out, until the token expiration time. However, every time the user would request something, the database would have to be consulted to check if his token is blacklisted, lengthening the process, and making your API stateful.
You can generate a new token that it already expired i.e. expiration is 1sec. and pass it to the user. Any upcoming request will be invalid. This is not optimal solution though..

OAuth REST access_token and instance_url expiry time?

I am working with Oauth2.0. In that i could able get the access_token and instance_url. Is there any expiry time for these two.
Can I store them and use it for all my REST calls without getting the new access_token and the instance_url. Is it possible for me to use it for long hours or even days.
The access token is only valid for the length of a session (as defined in the Salesforce Org's settings — I believe the longest this can be is 8 hours without activity), as it's actually a session ID, that said, you should also be given a refresh token. The refresh token has a much longer lifetime and can be used to authenticate the user once the session has expired, without them having to enter any credentials — this allows you to do it in the background without them even having to concern themselves with the login process.
model metrics do a good job of explaining the token flow here.