【发布时间】:2020-09-26 00:48:28
【问题描述】:
令牌过期时出现这样的错误
io.jsonwebtoken.JwtException: JWT expired at 2020-09-18T19:08:08Z. Current time: 2020-09-22T20:26:51Z, a difference of 350323563 milliseconds. Allowed clock skew: 0 milliseconds.
我创建了一个实现 AuthenticationEntryPoint 的类
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException {
ObjectMapper mapper = new ObjectMapper();
ErrorDetails errorDetails = ErrorDetails.builder()
.details(String.valueOf(e.getClass()))
.message("JWT has expired")
.timestamp(DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss", Locale.ENGLISH)
.format(LocalDateTime.now()))
.build();
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
httpServletResponse.setContentType("application/json");
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.getWriter().write(mapper.writeValueAsString(errorDetails));
}
在邮递员中我得到
{
"timestamp": "09-22-2020 20:26:51",
"message": "JWT has expired",
"details": "class org.springframework.security.authentication.InsufficientAuthenticationException"
}
从SecurityConfig配置方法
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling().authenticationEntryPoint(entryPoint)
.and()
.addFilterAfter(new JwtAuthorizationFilter(authenticationManager(), secret),
UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/api/credit/**").hasRole("USER")
.antMatchers("/api/auth/login").permitAll()
.anyRequest().denyAll();
http
.headers()
.addHeaderWriter(new StaticHeadersWriter("Content-Type", "application/json"));
}
有人可以建议我如何正确处理我在 IDE 中遇到的异常。
解决方案
在 JwtAuthorizationFilter 中
catch (ExpiredJwtException e) {
request.setAttribute("expired", e.getMessage());
}
在 CustomAuthenticationEntryPoint 中
if(httpServletRequest.getAttribute("expired") != null){
errorDetails.setMessage(String.valueOf(httpServletRequest.getAttribute("expired")));
}
【问题讨论】:
-
将您的代码发布到您创建 jwt 令牌的位置。这是因为过期时间。
-
@SurajGautam 在过期后尚未创建新令牌。我不知道我是否会这样做,因为我在 ApiGateway 中检查令牌并在另一个服务中创建令牌
-
如果令牌可以自动更新,您应该捕获异常并为用户更新令牌。否则,只需返回登录页面供用户重新登录。
-
我明白,但现在我想知道如何处理这样的错误
-
好的。请参阅下面的答案。
标签: spring spring-security jwt