是否可以在 Spring Boot 中配置 OAuth2 以使用 JSON 而不是 HTML 响应 InvalidTokenException?

Is it possible to configure OAuth2 in Spring Boot to respond with JSON instead of HTML for InvalidTokenException?

我的 Spring 引导应用程序使用 OAuth2 进行安全和令牌管理。我正在使用无效令牌查询我的 REST 端点之一,以使用 Postman 测试其响应。端点正确响应 401 InvalidTokenException,但当我希望它响应 JSON 时,响应内容是 HTML。这可以通过代码完成吗?

示例响应

<InvalidTokenException> 
    <error>invalid_token</error> 
    <error_description>Access token expired: … my token… </error_description> 
</InvalidTokenException>

将自定义 AuthenticationFailureHandler 添加到您的安全配置,然后在您的自定义实现中准备响应:

http.oauth2Login()
    .failureHandler(customFailureHandler)

故障处理程序示例:

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

详细说明 zfChaos 的答案,这是一个很好的线索,但没有提供足够的信息使响应成为 JSON 响应:

您还应该设置内容类型和字符编码。 然后,写下你的 JSON 响应(在这个例子中我使用了一个简单的字符串,当然使用 class 和 ObjectMapper 会更方便)。

这是一个完整的例子:

@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\" }");
                        })
                );
    }
}