How do I handle JWT token expiration?
Asked Answered
E

1

9

I am implementing jwt with Spring Boot. We have created a structure in which a user who has logged in once has the issued token value and sends the token value when logging in again. The expiration time is set to one day (86400 seconds).

ExpiredJwtException io.jsonwebtoken.ExpiredJwtException: JWT expired at 2021-11-21T04:25:31Z. Current time: 2021-11-22T03:45:58Z, a difference of 84027224 milliseconds.  Allowed clock skew: 0 milliseconds.

The above exception was thrown for an expired token. Since this token has expired, I want to refresh the token to issue a new token to the user. What should I do?

Electromotor answered 22/11, 2021 at 3:52 Comment(1)
What you want is Oauth2 implementation where, you have refresh token along with access token, access token is short live token can expired in some hours based on configuration, while refresh token use for generate new access token. and continue current functionality.Zymometer
S
10

In short, you need to use REFRESH_TOKEN when ACCESS_TOKEN expires to get a new ACCESS_TOKEN.

JWT has two kind of tokens: ACCESS_TOKEN and REFRESH_TOKEN.

ACCESS_TOKEN: When a user logins in, the authorization server issues an access token, which is an artifact that client applications can use to make secure calls to an API server.

REFRESH_TOKEN: ACCESS_TOKEN has short lifespan. So when ACCESS_TOKEN expires REFRESH_TOKEN is used to get a new ACCESS_TOKEN.

So in summary when authorization is successful you need to issue two token ACCESS_TOKEN and REFRESH_TOKEN. When ACCESS_TOKEN expires you need to call another api with REFRESH_TOKEN to get new ACCESS_TOKEN.

The client application can get a new access token as long as the refresh token is valid and unexpired. Consequently, a refresh token that has a very long lifespan could theoretically give infinite power to the token bearer to get a new access token to access protected resources anytime. So you need to set a policy for how long you want to give ACCESS_TOKEN for a given REFRESH_TOKEN.

Speculative answered 22/11, 2021 at 6:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.