Does it make sense to store JWT in a database?

I implemented a basic authentication system with Spring Boot, Spring Security, OAUTH2 and JWT as authentication tokens. This works well, but I thought it would make sense to store the JWT in the database and check if a token exists every time someone makes an authenticated request using it? I was thinking specifically about the following scenario: a user authenticates on a mobile device and they lose it, so they want to unauthorize this device. Then they can perform an operation that clears tokens issued to their user ID and deauthorize all tokens assigned to it. Any other way? Am I thinking wrong or offensive about this?

This is to provide a REST API to be called from the mobile APP.

+8
spring security rest jwt
source share
2 answers

You can save JWT in db, but you will lose some of the benefits of JWT. JWT gives you the advantage of not having to check the token in db every time, as you can just use cryptography to make sure the token is legal. If you need to find a token in db, you can simply use an opaque token that does not carry information with you, and let the server and database provide you with information. On the other hand, if you are going to store a token in db, I don't think JWT is a bad choice for your type of token. As you say, there are benefits to revocation if you store your token in db. It all depends on what you want to achieve (faster authorization, etc. And the ability to cancel on demand).

You can still use JWT with OAuth2 without storing tokens in db if you want. JWTs have a custom expiration time that you can set, after which they are invalid. Access tokens (whether JWT or not) should usually be short-lived for security. If the problem is that someone stole the phone and gained access to the tokens, I think the solution is to get those tokens to expire quickly (30 minutes?). If you use oauth2, the way to stop someone from continuing to use the application is to allow the real owner to cancel authorization of the mobile application client on the authorization server so that no more access tokens are issued.

+12
source share

You can set the expiration date (for mobile 1 week). Add a custom refreshId field for the user (you can use uuid for this). The next parameter is Issued at Claim ("iat"). Store refreshId in db and set it as a request parameter. Then, every time you check the token, you must check the age marker. If this is more than one hour, you should download data from the database and check the refreshId value and create a new token with the current value "iat" and send it to your mobile device. When you need to deactivate tokens, just create a new value for refreshId in db. After an hour, all tokens will be incorrect, so the user will need to log into the system on each device again. You can make more custom decisions if you need to.

+3
source share

All Articles