[英]Handling JWT Exception in Spring MVC
我正在尝试在REST Api上实现令牌身份验证,目前我指的是这篇文章 。 在文章中讨论了使用创建令牌JWT的问题,但我当前的问题是,每次将无效令牌传递给我的应用程序时,都会创建一个异常,即JwtException.class,我想捕获该异常使用我的全局异常处理程序类。 我还尝试将JwtException包装在我的应用程序的异常类中,但无效但未捕获异常。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value={JwtException.class})
public ResponseEntity<?> handleTokenException(JwtException e){
return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
}
@ExceptionHandler(value={InvalidAuthTokenException.class})
public ResponseEntity<?> handleTokenException(InvalidAuthTokenException e){
return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
}
}
您的GlobalExceptionHandler不是真正的全局,它只会捕获控制器中发生的异常(因此是ControllerAdvice ),您遇到的异常发生在servlet过滤器中,这是Spring Security几乎完成所有工作的地方。 这个小图表可能有助于解释我在说什么:
PreFilters < - 在进入控制器之前执行,JWT的解密正在这里发生
Controller < - ControllerAdvice将捕获此处抛出的所有异常
PostFilters < - 退出控制器后执行
幸运的是,Spring Security已经有了一些机制来处理在过滤器中解密JWT等事情时发生的异常。 您将需要像这样更新SpringSecurityConfig。 注意它的重要的是,是的ExceptionTranslationFilter您StatelessAuthenticationFilter(或任何你命名,其中JWT解密发生在过滤器) 之后 。
@Configuration
@EnableWebSecurity
@Order(2)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
ExceptionTranslationFilter = new ExceptionTranslationFilter(new AuthenticationExceptionHandler());
http.addFilterAfter(new StatelessAuthenticationFilter(tokenAuthenticationService),
ExceptionTranslationFilter.class);
}
}
public class AuthenticationExceptionHandler implements AuthenticationEntryPoint {
public void commence(HttpServletRequest request, HttpServletResponse, AuthenticationException e) throws IOException, ServletException {
//Logic on how to handle JWT exception goes here
}
}
public class StatelessAuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
//DECRYPT YOUR JWT
} catch (Exception e) {
throw new AuthenticationException();//If you get an exception wrap it in a AuthenticationException (or a class that extends it)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.