2013-12-08 94 views
2

我想安全基於CXF的休息API與春季安全。儘管我的配置在技術上有效,但我似乎無法使用JSON響應JSON而不是HTML消息。基於其他一些SO帖子,我使用groovy爲彈簧安全配置組織了以下java配置:春季安全http基本auth與Java配置休息api

@Configuration 
@EnableWebSecurity 
@Slf4j 
class SecurityConfig extends WebSecurityConfigurerAdapter { 

    protected void configure(HttpSecurity http) { 
     http.antMatcher('/api/**') 
       .authorizeRequests() 
       .antMatchers('/api/admin/**').hasRole('ADMIN') 
       .antMatchers('/api/**').hasRole('USER') 
       .and() 
       .httpBasic() 
       .and() 
       .addFilterBefore(
        new BasicAuthenticationFilter(authenticationManager: authenticationManager(), authenticationEntryPoint: new BasicJsonEntryPoint(realmName: 'Local')), 
        BasicAuthenticationFilter.class 
       ) 
    } 

    static class BasicJsonEntryPoint extends BasicAuthenticationEntryPoint { 

     @Override 
     public void commence(HttpServletRequest req, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException { 
      log.debug 'Handling response' 
      response.addHeader HttpHeaders.WWW_AUTHENTICATE, /Basic realm="${getRealmName()}"/ 
      response.setStatus HttpStatus.UNAUTHORIZED.value() 
      response.getWriter().println([status: HttpStatus.UNAUTHORIZED.value(), message: e.getMessage()].toJson()) 
     } 
    } 
} 

我已經嘗試過這種通用方法的多種變體,但不管我從API獲取HTML的方式。請參閱下面的請求/ RESP:

<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> 
     <title>Error 401 Full authentication is required to access this resource</title> 
    </head> 
    <body> 
     <h2>HTTP ERROR 401</h2> 
     <p>Problem accessing /api/test. Reason: 

      <pre> Full authentication is required to access this resource</pre> 
     </p> 
     <hr /> 
     <i> 
      <small>Powered by Jetty://</small> 
     </i> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
     <br/> 
    </body> 
</html> 

回答

0

我只是猜測這裏,但碼頭是有點太大的幫助,有時當你的應用程序發出比200S其他HTTP響應代碼。我的建議是,你添加一些邏輯到你的web.xml中以使Jetty的幫助短路。使我的應用程序脫離類似問題的完整技術記錄在:How do I suppress Jetty 8's default ErrorHandler?

祝你好運。

+0

這似乎不能解決問題。我嘗試過使用Jetty,Tomcat和Undertow。相同的結果。 – Todd