如何强制Spring Security OAuth 2使用JSON而不是XML?
我创建的Spring MVC应用程序,并成立了春季安全的OAuth 2 虽然从我布劳尔调用方法,我得到XML:如何强制Spring Security OAuth 2使用JSON而不是XML?
<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>
浏览器发送下面的标头:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
当我设置JSON接受头我得到JSON。我需要强制我的授权服务器始终发送JSON。还没有找到任何解决方案。谢谢。
春季安全的OAuth的异常使用的DefaultOAuth2ExceptionRenderer
渲染这将接收到的接受HTTP标头靠在提供了MessageConverter匹配。在你的情况下,似乎Spring Boot已经自动分配了XML和JSON MessageConverters。这种行为被证实,基于Accept头您收到在适当的Content-Type
呈现没有接受头部异常DefaultOAuth2ExceptionRenderer默认为接受:*和第一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
设置Accept: application/json
作为标题属性
这很容易给力的OAuth2,你只需要自己看着办吧第一个:
@Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.access("#oauth2.hasScope('read')")
.and()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler);
}
然后你会n EED创建您的AuthenticationEntryPoint和accessDeniedHandler @Bean
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return new AccessDeniedHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
response.getWriter().append("\"FORBIDDEN\"");
response.setStatus(HttpStatus.FORBIDDEN.value());
}
};
}
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
return new AuthenticationEntryPoint() {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.getWriter().append("\"UNAUTHORIZED\"");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
}
};
}
随意在JSON你喜欢的方式进行转换,我建议你杰克逊。
非常好...这工作。 –