Personalice la respuesta de error de OAuth2 en la autenticación del cliente con Spring Security

Si bien esto parece ser una tarea fácil, resulta todo lo contrario. Estoy tratando de personalizar el manejo de errores para las solicitudes de autenticación del cliente OAuth2. El propósito de esto es eliminar la excepción stacktrace / message del mensaje de respuesta.

Contextoimplementación de vainilla Oauth2 Spring SecurityConfiguración de Java SpringPasos para realizar la tarea.Crear una implementación personalizada deOAuth2ExceptionRenderer

Crear un@Bean en vez deOAuth2AuthenticationEntryPoint

@Bean
public OAuth2AuthenticationEntryPoint clientAuthEntryPoint()
{
    OAuth2AuthenticationEntryPoint clientEntryPoint = new OAuth2AuthenticationEntryPoint();
    clientEntryPoint.setTypeName("Basic");
    clientEntryPoint.setRealmName("my-realm/client");
    clientEntryPoint.setExceptionRenderer(new CustomOAuth2ExceptionRenderer());
    return clientEntryPoint;
}

Crear un controlador de acceso denegado

@Bean
public OAuth2AccessDeniedHandler accessDeniedHandler()
{
    OAuth2AccessDeniedHandler adh = new OAuth2AccessDeniedHandler();
    adh.setExceptionRenderer(new CustomOAuth2ExceptionRenderer());
    return adh;
}

Aumentar elAuthorizationServerSecurityConfigurer, entre otros, con estas implementaciones especializadas enAuthorizationServerConfiguration

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter
{
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception
    {
        oauthServer.authenticationEntryPoint(clientAuthEntryPoint());
        oauthServer.accessDeniedHandler(accessDeniedHandler());
        oauthServer.realm("my-realm");
    }
}
Solicitud OAuth2

Usamos curl para iniciar las solicitudes de OAuth2. Aquí está el comando que usamos para probar la autenticación del cliente:

curl --insecure -H "Accept: application/json" -X POST -iu adfadsf:asdvadfgadf "https://localhost:8430/oauth/token?grant_type=password$username=john&pasword=johny"
Comportamiento observado

Dado que la autenticación del cliente es una autenticación básica, Spring Security asignará unBasicAuthenticationFilter a ese paso Si tiene un error en el back-end relacionado con este paso (por ejemplo, excepción de SQL), Spring Security no recogerá elOAuth2AuthenticationEntryPoint y volverá a un punto de entrada predeterminadoBasicAuthenticationEntryPoint.

Registros
o.s.s.authentication.ProviderManager     : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
o.s.s.w.a.www.BasicAuthenticationFilter  : Authentication request for failed: org.springframework.security.authentication.InternalAuthenticationServiceException: show me the money
s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]
s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using default entry point org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint@649f92da
s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed```

Respuestas a la pregunta(1)

Su respuesta a la pregunta