我已经创建了 Spring MVC 应用程序并设置了 Spring Security OAuth 2。 从我的浏览器调用方法时,我得到 XML:
<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>
浏览器发送以下 header :
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
当我设置 json 接受 header 时,我得到 JSON。我需要强制我的授权服务器始终发送 JSON。还没有找到任何解决方案。谢谢。
最佳答案
对于 Spring Security,OAuth 异常是使用 DefaultOAuth2ExceptionRenderer 呈现的
它将接收到的 Accept HTTP header 与提供的 MessageConverter 进行匹配。在您的情况下,Spring Boot 似乎已自动分配 XML 和 JSON MessageConverters。此行为已确认,基于 Accept header ,您正在接收以正确的 Content-Type 呈现的异常
如果没有 Accept header ,DefaultOAuth2ExceptionRenderer 默认为 Accept: * 并且通常响应的第一个 MessageConverter 是 XML。
如果 XML 在您的应用中不受欢迎,您将需要了解为什么它得到支持(很可能您的类路径中有 FasterXML Jackson)。
如果您想同时支持两者但希望默认使用 JSON,这将要求您编写自己的 OAuth2ExceptionRendrer 实现并确保以 JSON 呈现异常。更好的方法是将您的 impl 挂接到 ContentNegotationManager 并将 MediaType 解析委托(delegate)给它。
有关 ContentNegotationManager 的更多信息,请查看此链接:
https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc
关于java - 如何强制 Spring Security OAuth 2 使用 JSON 而不是 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33929788/