How do you handle jwt token expiration?

github logo Updated on ・1 min read

Let's say we have the following scenario: A user login with correct credentials and he gets a token with expiration date. After some time
(lets say 30 minutes) the token is expired and the user has to give again his credentials to be authorized. Our Goal is to not force the user give his username and password again.

How would you handle this problem? 😉

twitter logo DISCUSS (4)
markdown guide
 

Let me understand, you are asking for a refresh token for such expired token right?

I would do it with OAuth 2.

Client asks for authorization -> User authenticates -> Server issues an expiring access token (the jwt) and a refresh token -> User does their business -> Token expires -> client exchanges the refresh token with a new access token

Basically you can just use OAuth, the only difference is the token instead of being a random string it's a "speaking" JWT token with all the attributes you insert into it.

Example: developer.atlassian.com/cloud/jira...

 
 

How is this advantageous over setting the expiration duration to like a month ?

 

Well, it doesn't fit the requirements :) Also, it can be a security liability, depending on the ability of the server to expire/invalidate the content of the access token. This is a good overview of three strategies: Access Token Lifetime

The first strategy is the one I was talking about: short expiration for tokens, long for refresh tokens. The second is the one where you make tokens expire and make the user login often (but it defies the requirements), the third one is the one where the token never expires but it strongly depends on the infrastructure and the ability to revoke tokens

Classic DEV Post from Feb 8

Why you may need a dedicated homelab.

When that good ol' PC won't cut it anymore.

Nikos Kanakis profile image
I am a Web Developer with knowledge of both front-end and back-end programming languages. True believer on teamwork and open source community.