Open jgrandja opened 2 years 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;
}
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;
}
Publish a guide on How-to: Handle errors and customize the OAuth 2.0 Error response
Related gh-499