spring-projects / spring-authorization-server

Spring Authorization Server
https://spring.io/projects/spring-authorization-server
Apache License 2.0
4.87k stars 1.29k forks source link

How-to: Handle errors and customize the OAuth 2.0 Error response #541

Open jgrandja opened 2 years ago

jgrandja commented 2 years ago

Publish a guide on How-to: Handle errors and customize the OAuth 2.0 Error response

Related gh-499

jgrandja commented 9 months ago

Sample demonstrating how to customize the error response parameters using OAuth2ErrorAuthenticationFailureHandler:

private AuthenticationFailureHandler authenticationFailureHandler = createAuthenticationFailureHandler();

private static AuthenticationFailureHandler createAuthenticationFailureHandler() {
    OAuth2ErrorHttpMessageConverter errorResponseConverter = new OAuth2ErrorHttpMessageConverter();
    errorResponseConverter.setErrorParametersConverter(error -> {
        Map<String, String> parameters = new HashMap<>();
        // Only return the error code
        parameters.put(OAuth2ParameterNames.ERROR, error.getErrorCode());
        return parameters;
    });

    OAuth2ErrorAuthenticationFailureHandler authenticationFailureHandler = new OAuth2ErrorAuthenticationFailureHandler();
    authenticationFailureHandler.setErrorResponseConverter(errorResponseConverter);

    return authenticationFailureHandler;
}
jgrandja commented 9 months ago

Sample demonstrating how to customize the HTTP status for the error response using OAuth2ErrorAuthenticationFailureHandler:

private AuthenticationFailureHandler authenticationFailureHandler = createAuthenticationFailureHandler();

private static AuthenticationFailureHandler createAuthenticationFailureHandler() {
    OAuth2ErrorHttpMessageConverter errorResponseConverter = new OAuth2ErrorHttpMessageConverter() {
        @Override
        protected void writeInternal(OAuth2Error error, HttpOutputMessage outputMessage)
                throws HttpMessageNotWritableException {

            HttpServletResponse servletResponse = ((ServletServerHttpResponse) outputMessage).getServletResponse();
            if (OAuth2ErrorCodes.INVALID_CLIENT.equals(error.getErrorCode())) {
                servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
            } else {
                servletResponse.setStatus(HttpStatus.BAD_REQUEST.value());
            }
            super.writeInternal(error, outputMessage);
        }

    };

    OAuth2ErrorAuthenticationFailureHandler authenticationFailureHandler = new OAuth2ErrorAuthenticationFailureHandler();
    authenticationFailureHandler.setErrorResponseConverter(errorResponseConverter);

    return authenticationFailureHandler;
}