Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force Spring Security OAuth 2 to use JSON instead of XML?

I've created Spring MVC application and set up Spring Security OAuth 2. While calling methods from my brower i get XML:

<oauth>
    <error_description>
        Full authentication is required to access this resource
    </error_description>
    <error>unauthorized</error>
</oauth>

Browser sends following header:

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

When I set json accept header I get JSON. I need to force my authorization server always send JSON. Haven't found any solution. Thanks.

like image 752
Taras Avatar asked Nov 26 '15 02:11

Taras


2 Answers

For Spring Security OAuth exceptions are rendered using the DefaultOAuth2ExceptionRenderer

It's going to match the received Accept HTTP header against the provided MessageConverters. In your case it seems that Spring Boot has automatically assigned XML and JSON MessageConverters. This behaviour is confirmed that based on the Accept header you are receiving the exception rendered in a proper Content-Type

Without the Accept header DefaultOAuth2ExceptionRenderer defaults to the Accept: * and the first MessageConverter usually to respond is XML one.

if XML is undesirable in your app you'll need to see why it's getting supported (most likely you have a FasterXML Jackson in you classpath).

If you want to support both but want to have JSON default that will require you to write your own impl of the OAuth2ExceptionRendrer and ensure that exceptions get rendered in JSON. Even better approach would be to hook your impl to the ContentNegotationManager and delegate MediaType resolution to it.

For more info on ContentNegotationManager check this link:

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

like image 194
vmarusic Avatar answered Oct 17 '22 23:10

vmarusic


Set Accept: application/json as the header attribute

like image 45
user7365624 Avatar answered Oct 17 '22 23:10

user7365624