Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security prolong JWT token expiration for each request

In our application we have to set expiration duration for JWT token to 10 mins. If the user calls the API within 10 mins, it will be valid, beyond that it will throw invalid token exception.

The catch is, if the user invokes the API at the 9th minute, the token validation should be extended to next 10 mins. So, we have to prolong the token expiration for each request to next 10 mins (more like Http sessions).

We use spring security AuthenticationProvider to do the validation, but not sure how to update the expiration time and send the updated token in response header. How we can achieve this in sprint security?

Thanks.

like image 643
Raj Avatar asked Dec 09 '16 10:12

Raj


People also ask

How can I extend my JWT token expiry?

A good pattern is to refresh the token before it expires. Set the token expiration to one week and refresh the token every time the user opens the web application and every one hour. If a user doesn't open the application for more than a week, they will have to login again and this is acceptable web application UX.

How do I handle JWT expiry?

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.


1 Answers

We couldn't find any solution to update the token and add it to response header in Spring Security. But the same can be achieved by implementing ResponseBodyAdvice interface and annotating the implementation class with @ControllerAdvice.

Hope this helps someone else.

like image 186
Raj Avatar answered Oct 21 '22 09:10

Raj