我想出了如何自定义 DefaultOAuth2AuthorizedClientManager 的失败处理程序,但它实际上并没有实现我的最终目标,即在尝试使用过期的刷新令牌从认证服务器。
要处理 OAuth2AuthorizationException,请使用带有 @ExceptionHandler(OAuth2AuthorizationException.class) 注释的方法创建一个 @ControllerAdvice 类,该方法可以执行您想要的任何操作。这是我所做的:
@ControllerAdvice
public class GlobalControllerAdvice {
/**
* spring-security-oauth2 automatically refreshes the access token while resolving
* \@RegisteredOAuth2AuthorizedClient-annotated parameters to @RequestMapping methods. When it
* fails to refresh an OAuth2 access token because the refresh token is expired,
* RefreshTokenOAuth2AuthorizedClientProvider.authorize() throws an OAuth2AuthorizationException.
* If we didn't handle it here, we'd respond with a HTTP 500, and that's no good. Instead, we
* respond with HTTP 403 so that the UI can log itself out.
*/
@ExceptionHandler(OAuth2AuthorizationException.class)
ResponseEntity<?> handleHttpStatusCodeException(OAuth2AuthorizationException e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
}
如果出于某种原因您想要自定义 DefaultOAuth2AuthorizedClientManager 故障处理程序,您可能需要创建一个全新的 OAuth2AuthorizedClientArgumentResolver bean(如下所示)并通过 WebMvcConfigurer 注册它(如下所示):
@Bean
@Order(0)
public OAuth2AuthorizedClientArgumentResolver oAuth2AuthorizedClientArgumentResolver(OAuth2AuthorizedClientManager oAuth2AuthorizedClientManager) {
final OAuth2AuthorizedClientArgumentResolver oAuth2AuthorizedClientArgumentResolver = new OAuth2AuthorizedClientArgumentResolver(oAuth2AuthorizedClientManager);
return oAuth2AuthorizedClientArgumentResolver;
}
@Bean
public OAuth2AuthorizedClientManager oAuth2AuthorizedClientManager(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientRepository authorizedClientRepository) {
final DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizationFailureHandler(new OAuth2AuthorizationFailureHandler() {
@Override
public void onAuthorizationFailure(OAuth2AuthorizationException e,
Authentication authentication, Map<String, Object> map) {
// Handle auth failure here
}
});
return authorizedClientManager;
}