Revoke refresh token - jwt

I am currently build a security service that issue jwt token and refresh token using asp.net and microsoft jwt library. My question are, I have refresh token from users that store in db:
Should I replace refresh token each time user request for new access token by using current refresh token or just mark that refresh token that is revoked or some kind of flag?
Should I delete or mark it with flag when there is a request for revoking token?
Thanks.

One standard way of dealing with blacklisted JWT tokens is to maintain a blacklist cache of tokens which should no longer be honored. You would typically engineer the setup such that the number of JWT inside the blacklist cache at any given time would be relatively small. Since a cache is reasonably fast (about 100 times faster than a database lookup), checking the cache with each incoming request is not a performance killer.
The workflow for an incoming JWT would then be modified to this:
Check the claims of the incoming JWT (e.g. exp)
Check the checksum, to make sure client has not tampered with the JWT
Hit the blacklist cache, verify that JWT has not been revoked
Grant access to server side system
Regarding grooming the blacklist cache, one common approach is to assign an expiry time to each JWT. Then, when a given access or refresh token expires, it can be removed from the cache. Redis, as an example, supports automatic deletion of stale cache entries using expiry time.

Related

What is the point of refresh token in jwt?

Please don't mark as duplicate I came through a lot of questions like this but still I didn't get the point of refresh token. Some of the reason they said are:
If an attacker gets the access token it will expiry soon
But where I am confused is if the attacker was able to get the access token why they wouldn't be able to get the refresh token (both of them needed to access token by JS to sent request so they needed to store in local storage)
If the attacker gets the refresh token we can block it in server.
But we can also block the access token in server right. (with DB)
Note I am not talking about OAuth refresh token, because as per the answers I read,
The idea of refresh tokens is that if an access token is compromised,
because it is short-lived, the attacker has a limited window in which
to abuse it.
Refresh tokens, if compromised, are useless because the attacker
requires the client id and secret in addition to the refresh token in
order to gain an access token.
So it makes sense here but what about JWT?
Typically the access token gets sent with every request, and to your API.
Typically a refresh token only gets sent once, immediately expires after use and only goes to your authentication server. All these measures generally reduce risk.
JWT and OAuth2 can be used together, and it's highly recommended to use OAuth2 instead of trying to write something from scratch.
I talk a bit more about the pitfalls in my article: https://evertpot.com/jwt-is-a-bad-default/
The refresh token allows the client to make a call and ask for a new access token. For setups where the access token does have a certain expiry, the refresh token will typically have an expiry which is later than the access token itself. Here is a typical workflow using access and refresh tokens:
The client authenticates to the server via 1FA or 2FA
The server responds with an access token having an expiry in 5 minutes, along with a refresh token which expires a minute later
The client then uses the access token as needed.
When authentication fails using the current access token, under the hood the client will take the refresh token and hit the server to get a new access token. We then go to step #2 above and recycle.
Note that for certain instances, the refresh token is not needed. One example would be sites like Stack Overflow, which uses token which never expire. Another example would be certain high security sites such as banking sites. In these cases, the site might force you to reauthorize via 1FA/2FA in order to keep the session going.
One way in which an update of the authentication token can be carried out through another and without exposing it to client applications (avoiding its use in a malicious way), is to store it in a cache system such as REDIS and in the When the request token has expired, check in storage if the user has a refresh token that allows him to regenerate the authentication. This could be implemented within the same middleware that validates the token that accompanies the request or in an endpoint intended for this purpose.

API rest with jwt for authentication. Why do we need a refresh token?

So, i'm trying nest js for a side project. Reading a lot lately about jwt authentication flow. Conceptually, the flow would be something like:
Client logs in and receives and access token and a refresh token. Access Token will be short lived and will be stored in memory, not in localstorage, to reduce the risks of being stolen.
Refresh token will be used only when the access token is expired to get a new one. The new one will be stored in memory. The refresh token will be stored in an httpOnly cookie, so no javascript access will be allowed hence improving the security.
Everything is cristal clear, but, my question is... why do we need the access token and why don't we always use the refresh token? In the end, if we are trusting the refresh token to generate new access tokens... why don't we simplify the whole thing and use only the long lived, stored in an httpOnly cookie on every request?
I mean I get the whole process, I just don't get why is not "secure" to use the token stored in an httpOnly cookie every time.
Can anyone share some light here?
Thanks!
You use the access token to access the API. It contains the necessary claims to authenticate and authorize the request.
The refresh token is a separate token that you use to renew the access token and you can not use the refresh token to access any API, as it is typically just a random string without any specific meaning (no claims).
The refresh token is never sent to any API and having separate tokens gives a better separation of concerns. By using refresh tokens, we can have short-lived access tokens, so if the access token is stolen, it can only be used for a short time. The refresh token is stored in a more secure way and it is only used between the client and the identity provider, so there is less risk that it will be stolen or intercepted.
Some platforms (like ASP.NET core) stores the token by default in the session cookie) but to secure it it is encrypted using strong encryption. This means that the hacker or browser can't see the actual tokens inside the cookie.
More you travel, more you exposed.
As you know the refresh token is meant to be used in case of short lived access token expiration. The idea for the use of two tokens is very simple. As access token (short lived token) will travel more frequently over the wire, increasing it chances of getting it caught by external parties. Therefore, short life expectency of access token will deny the access to the resouces for longer run in case of compromisation.
If the refresh token is secured, why don't we use just the refresh on
every request?
Nothing can make the refresh token secure. It's totally client responsibility to store it in secure location/storage for later use.

is it a good idea to put expired tokens to blacklist table?

To begin with this is how my current auth flow looks
User logs in
User gets a refresh_token assigned and stored in the database (long lived 7d)
Client receives an accestoken (Short lived, 2h), and stores it as a cookie. Client also receives the userId AES encrypted, and stores
it as a cookie.
As far as the access token is not expired, the user keeps using the token to navigate the website
The token expires
The expired access token gets send to a refresh endpoint, so is the userID (Aes encrypted) both currently stored in out cookies.
The server decrypts the userId and retrieves the refreshtoken that corresponds to the user by selecting the refresh token from the database using out userId.
Now we have in the server our refreshtoken and accestoken, so we refresh the token, and send back the new accesstoken. We also generate a new refreshtoken and overwrite our old refreshtoken in the database with the new one.
My question is basically related to that last step. Since those refresh tokens are still technically valid, since they have a long expiration time. Can I create a table in my database named "blacklisted_tokens" or something like that, and store there the values of the token? And then right before generating a new access token it should prior to that check if that refresh token is or isnt in that database, meaning that it will be blacklisted.
This is the authflow diagram
My question is basically related to that last step. Since those
refresh tokens are still technically valid, since they have a long
expiration time. Can I create a table in my database named
"blacklisted_tokens" or something like that, and store there the
values of the token? And then right before generating a new access
token it should prior to that check if that refresh token is or isnt
in that database, meaning that it will be blacklisted.
it's not recommended to do that as because, probability of generating 2 same token is low and adding NOT necessary additional processes to your back-end is not a good idea and has performance issue in large scale Token re-generation(a lot of users).
And also, Tokens are along with an identity(id) in which reduces security risks.
if i were you, i would just re-write new-token to old-token.
The most important type of cyber attack which threaten Tokens is The Sniffing attack and by doing below steps actually the probability of this attack goes almost to zero:
SSL certificate
Expiring Token and re-generation
Salty requests
Salt
In cryptography, a salt is random data that is used as an additional
input to a one-way function that hashes data, a password or
passphrase. Salts are used to safeguard passwords in storage.

JWT and blocking users

JWT is a stateless authentication mechanism as the user state is never saved in server memory.
How to invalidate the token if administrator blocks the user for some resons?
JWT is not an authentication mechanism but a token format. Since JWT are self-contained, you CAN use them for stateless authentication. However, this does not mean that your authentication mechanism MUST be stateless (although there it has its benefits).
There are several options for handling user lockout / revoking authorization:
Do a lookup of the user in every request after validating the JWT to see if the user is locked out
Access tokens are supposed to be short-lived, so you can look up the user the next time a new access token is requested (e.g., using a refresh token) and then refuse issuing a new access token
Alternatively, you can blacklist all tokens issued for a specific user by storing their jti in a database. See also: https://auth0.com/blog/denylist-json-web-token-api-keys/. EDIT: As pointed out in the comments, while not strictly stateless, this approach is still efficient, because a blacklist only needs to store blacklisted tokens for the duration of their lifetime, and lookup should be highly efficient.
You can look up the user identified by a specific JWT every N requests or whenever X percent of the lifetime of the JWT has passed rather than doing it in every request.
None of these approaches is entirely stateless. In general, stateless authorization is not possible if you want it to be possible to revoke authorization. If you want your tokens to be entirely stateless, you should make sure their lifetime is as short as possible, and issuing a new token is not stateless.

JWT for stateless API, but session control for security

I really want to use JWT for API access, to keep it stateless. But at the same time I need to have strong security recourse to deny tokens that are yet to expire.
For more sensitive user information APIs I can rely on forcing a fresh login, comparing the IP address, etc. But I still want to be able to revoke a users token if needed. I don't mind paying the overhead price.
What I imagined would be to have each user create their own secret key based on their password, and store it in the session. I don't mind trading the overhead for an easier way to deal with stolen tokens. This way a simple password reset should invalidate old tokens.
Acknowledging the trade off, does this method make sense? Are there better ways to go about this?
You should create a "blacklist" on your server. If a token needs to be revoked, place it in the blacklist and set it to expire from the list when the token expires. For every authentication attempt, you will verify that the incoming JWT is not in the blacklist. Redis can make this quite easy.
Alternatively, consider a third-party service such as Stormpath. Disclaimer: I work for Stormpath. We have an Oauth2 api that let's you issue access + refresh tokens (for a password grant flow). We handle revocation for you, so long as you don't mind the overhead of the REST call to verify the state of the token. Please see Using Stormpath for OAuth 2.0 and Access/Refresh Token Management. We have easy support for this in our Express-Stormpath .library
well, i just had the same kind of implementation. add hashed password to token, and when client returns the token, during validation, check if user's password has been changed in db, if user's hashed pass is not the same as the one you put in token, reject the token. In this way, you don't need to keep any info about user and/or token on the server.
I don't like the idea of white/black listing tokens, so I ended up using the users hashed password + another random key as their token's secret key:
+---------------+------------------------------------+-----------+
| email | password | key |
+---------------+------------------------------------+-----------+
| user#mail.com | asfsifj2fij4f4f4f8d9dfhs.8f8fhsd8h | r4nd0Mk3Y |
+---------------+------------------------------------+-----------+
I then keep a cache in memory of users id=>password+key to verify each users token. This way tokens can be discarded when: 1) user resets password; 2) application changes the user key.
This almost defeats the purpose of JWT's, but I need this layer of security for my use case.
JSON Web Token
JSON Web Token (JWT) is defined by the RFC 7519.
It's a standard method for representing claims securely between two parties. JWT is a self-contained token and enables you to store a user identifier, an expiration date and whatever you want (but don't store passwords) in a payload, which is a JSON encoded as Base64.
The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server.
Tracking your tokens
You won't need to persist JWT tokens if you don't need to track them.
Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token, you could persist the token identifier (the jti claim) and some metadata (the user you issued the token for, the expiration date, etc) if you need.
Your application can provide some functionality to revoke the tokens, but always consider revoking the tokens when the users change their password.
When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.
Additional information
When sending sensitive data over the wire, your best friend is HTTPS and it protects your application against the man-in-the-middle attack.
To find some great resources to work with JWT, have a look at http://jwt.io.