猿问

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

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

响应示例

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


炎炎设计
浏览 110回答 2
2回答

Cats萌萌

详细说明 zfChaos 的答案,这是一个很好的线索,但没有提供足够的信息来使响应成为 JSON 响应:您还应该设置内容类型和字符编码。然后,编写您的 JSON 响应(在本例中我使用了一个简单的 String,当然使用类和 an 会更方便ObjectMapper)。这是一个完整的例子:@Configurationpublic class SecurityConfiguration extends WebSecurityConfigurerAdapter {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void configure(HttpSecurity httpSecurity) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; httpSecurity&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .oauth2Login(login -> login&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .failureHandler((request, response, exception) -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response.setContentType("application/json");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response.setStatus(401);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response.setCharacterEncoding("UTF-8");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response.getWriter().write("{ \"msg\": \"foo\" }");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }}

慕工程0101907

将自定义添加AuthenticationFailureHandler到您的安全配置,然后在自定义实现中准备响应:http.oauth2Login()&nbsp; &nbsp; .failureHandler(customFailureHandler)失败处理程序示例:public class CustomFailureHandler extends SimpleUrlAuthenticationFailureHandler {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {&nbsp; &nbsp; &nbsp; &nbsp; response.sendError(401, "XML HERE");&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Html5
我要回答