使用JavaConfig进行Spring Security的简单演示

时间:2014-06-20 11:44:24

标签: spring-security spring-java-config

My Maven项目有一些集成测试需要满足一些简单的内存Spring安全性。

我有这个基于XML的配置工作正常,但现在我想在基于JavaConfig的配置中使用它:

<!-- A REST authentication -->
<http use-expressions="true" pattern="/admin/**">
    <intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')" />
    <http-basic entry-point-ref="restAuthenticationEntryPoint" />
    <logout />
</http>

<!-- A hard coded authentication provider -->
<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="stephane" password="mypassword" authorities="ROLE_ADMIN" />
        </user-service>
    </authentication-provider>
</authentication-manager>

我尝试了以下Java配置:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("stephane").password("mypassword").roles("ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .authorizeRequests()
    .anyRequest().authenticated()
    .and()
    .httpBasic();
}

但GET请求被拒绝访问:     测试失败:testGreetingSucceedsWithCorrectUserCredentials(com.thalasoft.learnintouch.rest.AdminControllerTest):预期状态:&lt; 200&gt;但是:&lt; 401&gt;

有任何线索吗?

亲切的问候,

Stephane Eybert

1 个答案:

答案 0 :(得分:0)

我可以使用以下配置修复安全性:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("stephane").password("mypassword").roles("ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .httpBasic()
    .authenticationEntryPoint(restAuthenticationEntryPoint)
    .and()
    .authorizeRequests()
    .antMatchers("/**").hasRole("ADMIN")
    .anyRequest().authenticated();
}

我错过了.authenticationEntryPoint(restAuthenticationEntryPoint)和.csrf(。。disable()配置。

测试现在按预期通过。