使用Java配置的Rest api的Spring security http basic auth

时间:2013-12-08 19:12:42

标签: spring api rest groovy basic-authentication

我正在尝试使用Spring安全性来保护基于CXF的rest API。虽然我的配置在技术上有效,但我似乎无法在401上使用JSON而不是HTML消息来响应API。基于其他一些SO帖子,我使用groovy将以下java配置放在一起用于spring安全配置:< / p>

@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。请参阅以下req / 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>

1 个答案:

答案 0 :(得分:0)

我只是在这里猜测,但是当你的应用程序发出超过200秒的http响应代码时,Jetty有点太有用了。我的建议是你在web.xml中添加一些逻辑来缩短Jetty的帮助。我的应用程序出于类似问题的完整技术记录在:How do I suppress Jetty 8's default ErrorHandler?

祝你好运。