I am trying to implements additional checks for a user which is exchanging code for tokens using "/oauth2/token" endpoint in Spring Authorization Server. And for this I need to provide custom error message, error code and provide specific http status(other than 400 or 500).
I see that the code exchange starts in OAuth2TokenEndpointFilter but it has a strict exception hanling like
private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException { ... }
and it can not be overridden as well as can not be set
private AuthenticationFailureHandler authenticationFailureHandler = this::sendErrorResponse;
So I can extend from OAuth2AuthenticationException but it does not suite as I can not control the status and the response body.
Ok, I should read doc more carefully.
I still have to extend from AuthenticationException but I also have full controll over failure so adding custom body/code/status
@Bean
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
new OAuth2AuthorizationServerConfigurer();
http.apply(authorizationServerConfigurer);
authorizationServerConfigurer
.tokenEndpoint(tokenEndpoint ->
((OAuth2TokenEndpointConfigurer)tokenEndpoint).errorResponseHandler(errorResponseHandler)// instance of AuthenticationFailureHandler
);
return http.build();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With