1

My Spring Boot application uses OAuth2 for security and token management. I’m querying one of my REST endpoints with an invalid token to test its response using Postman. The endpoint is correctly responding with 401 InvalidTokenException but the response content is HTML when I would like it to respond with JSON. Can this be done via code?

Example response

<InvalidTokenException> 
    <error>invalid_token</error> 
    <error_description>Access token expired: … my token… </error_description> 
</InvalidTokenException>
Space Cadet
  • 385
  • 6
  • 23
  • Can you clarify your Boot version and the OAuth dependencies? The reason is that Spring Security undergone a pretty massive change in their OAuth 2.0 support in the last couple of years. – jzheaux Apr 10 '20 at 22:30

2 Answers2

1

Add custom AuthenticationFailureHandler to your security configuration and then prepare response in your custom implementation:

http.oauth2Login()
    .failureHandler(customFailureHandler)

Failure handler example:

public class CustomFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        response.sendError(401, "XML HERE");
    }
}
zfChaos
  • 415
  • 4
  • 13
1

To elaborate on zfChaos's answer, which is a good lead but does not provide sufficient information for the response to be a JSON response:

You should also set the content type and character encoding. Then, write your JSON response (in this example I used a simple String, of course it would be more convenient use a class and an ObjectMapper).

Here is a complete example:

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .oauth2Login(login -> login
                        .failureHandler((request, response, exception) -> {
                            response.setContentType("application/json");
                            response.setStatus(401);
                            response.setCharacterEncoding("UTF-8");
                            response.getWriter().write("{ \"msg\": \"foo\" }");
                        })
                );
    }
}
Stav Shamir
  • 888
  • 7
  • 20