2

我創建的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。還沒有找到任何解決方案。謝謝。

回答

5

春季安全的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

2

設置Accept: application/json作爲標題屬性

+0

非常好...這工作。 –

0

這很容易給力的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你喜歡的方式進行轉換,我建議你傑克遜。

相關問題