Send a custom error message if token expired
Closed this issue · 3 comments
How to send a custom status code (or message) when the token has expired.
Tried subclassing the AuthenticationException subclass and threw exception in validateToken method. However it doesnt reach the commence method of the entry point class and the method instead throws 500 error.
Just had to deal with this and wanted to know whether there is a "best way to go".
I did the following:
If JwtAuthenticationTokenFilter catches an ExpiredJwtException, mark request as expired:
catch (ExpiredJwtException ex) {
request.setAttribute("expired", ex.getMessage());
}
And then in JwtAuthenticationEntryPoint we can perform a check:
final String expiredMsg = (String) request.getAttribute("expired");
final String msg = (expiredMsg != null) ? expiredMsg : "Unauthorized";
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
Using an expired token will result in something like:
{
"error": "Unauthorized",
"message": "JWT expired at 2017-11-16T14:26:52Z. Current time: 2017-11-17T15:09:22Z, a difference of 88950802 milliseconds. Allowed clock skew: 0 milliseconds.",
"path": "/bla/bla",
"status": 401,
"timestamp": 1510927762842
}
As far as I know, sending 401 - Unauthorized is the desired behavior for an expired token, but, of course adding useful information is always a good idea.
Yeah, you're right. I will add this to my dev queue as an enhancement.
Closed, because I published a complete new version.