如何强制Spring Security OAuth 2使用JSON而不是XML?

Tar*_*ras 5 java spring spring-mvc spring-security spring-security-oauth2

我已经创建了Spring MVC应用程序并设置了Spring Security OAuth 2.在从我的浏览器调用方法时,我获得了XML:

<oauth>
    <error_description>
        Full authentication is required to access this resource
    </error_description>
    <error>unauthorized</error>
</oauth>
Run Code Online (Sandbox Code Playgroud)

浏览器发送以下标题:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

当我设置json接受标头时,我得到了JSON.我需要强制我的授权服务器总是发送JSON.没有找到任何解决方案.谢谢.

小智 7

对于Spring Security,使用DefaultOAuth2ExceptionRenderer呈现OAuth异常

它会将收到的Accept HTTP标头与提供的MessageConverters进行匹配.在您的情况下,Spring Boot似乎已自动分配XML和JSON MessageConverters.此行为已得到确认,基于Accept标头,您将收到以适当的Content-Type呈现的异常

没有Accept标头DefaultOAuth2ExceptionRenderer默认为Accept:*,并且通常响应的第一个MessageConverter是XML.

如果您的应用程序中不需要XML,您将需要了解它为何得到支持(很可能您在类路径中有一个FasterXML Jackson).

如果你想支持两者,但想要使用JSON默认值,则需要编写自己的OAuth2ExceptionRendrer impl 并确保以JSON 格式呈现异常.更好的方法是将您的impl挂钩到ContentNegotationManager并将MediaType解析委托给它.

有关ContentNegotationManager的更多信息,检查以下链接:

https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc