與此問題類似,但沒有答案:Spring Security: Handle InvalidBearerTokenException in @ExceptionHandler
我有類似的代碼,我正在嘗試捕捉org.springframework.security.oauth2.server.resource.InvalidBearerTokenException, when a user has supplied invalid/expired/bad JWT格式。
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Autowired
@Qualifier("handlerExceptionResolver")
private HandlerExceptionResolver resolver;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException e) throws IOException, ServletException {
resolver.resolveException(request, response, null, e);
}
}
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
private CustomAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private CustomAccessDeniedHandler accessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception
{
// other config here
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.oauth2ResourceServer().jwt();
http.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler);
}
}
我還為自定義回應實作了@ExceptionHandlerof AuthenticationException。
@ExceptionHandler({AuthenticationException.class})
protected ResponseEntity<Object> handleAuthException(AuthenticationException ex, WebRequest req)
{
CustomResponse response = ...
return new ResponseEntity<>(response, ...);
}
InvalidBearerTokenException是 的子類AuthenticationException。知道為什么這段AuthenticationEntryPoint代碼沒有捕捉到它嗎?我也嘗試在方法中添加日志記錄,但在拋出commence時不會呼叫它,但其他會呼叫。InvalidBearerTokenExceptionAuthenticationException
uj5u.com熱心網友回復:
AuthenticationEntryPoint您必須在中指定它OAuth2ResourceServerConfigurer,如下所示:
@Override
protected void configure(HttpSecurity http) throws Exception
{
// other config here
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.oauth2ResourceServer().jwt()
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler);
}
當你設定它時,配置器會改變AuthenticationEntryPoint里面使用的那個BearerTokenAuthenticationFilter,見這里。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429146.html
標籤:爪哇 春天 弹簧靴 弹簧安全 spring-security-oauth2
上一篇:如何將RequestBody中的嵌套JSON轉換為物體
下一篇:無法使用前端dockerfile.v0解決:無法創建LLB定義:docker.io/bcgovimages/von-image:py36-indy1.3.1-dev-441-ew-s2i:未找到
