Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customise exception handling in Spring Authorization Server for token endpoint

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.

like image 443
Kafer Avatar asked Dec 19 '25 18:12

Kafer


1 Answers

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();
}
like image 172
Kafer Avatar answered Dec 24 '25 10:12

Kafer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!