【发布时间】:2018-05-15 17:30:51
【问题描述】:
我已经在我的控制器中使用 Spring Security 以经典方式设置了基本身份验证,如下所示:
@EnableWebSecurity
@EnableGlobalMethodSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("user").roles("USER")
.and()
.withUser("admin").password("admin").roles("USER", "ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(....);
}
}
说到测试点,我使用 @WithMockUser 来注释我的测试。 GET 的测试可能如下所示:
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = SomeController.class)
public class SomeControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void test1() {
mockMvc.perform(get(...)).andExpect(...);
}
或者像这样的 POST:
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = SomeController.class)
public class SomeControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void test1() {
mockMvc.perform(post(...)).andExpect(...);
}
然后意想不到的事情发生了:
- 当一个测试方法没有用@WithMockUser注释时,它会因为401状态(未授权)而失败,这是合理的,因为没有完成基本身份验证
- 当一个测试方法只是用一个空的 @WithMockUser 没有指定任何凭据进行注释时,它开始通过,这是不合理的,因为我没有提供正确的用于身份验证的数据(我将它们留空)
- 此时,当填写一些正确的凭据时,测试方法也通过了,例如 @WithMockUser(username = "user", password = "user", roles = "USER")
问题:发生了什么事?如何解决这种不当行为?
看起来 Spring Security 已激活,但是我的测试没有使用我期望使用的身份验证。我必须自己模拟身份验证数据吗?
EDIT完整的配置方法如下
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(URL1).hasAnyRole(ROLE_ADMIN)
.antMatchers(URL2).hasAnyRole(ROLE_USER)
.antMatchers(URL3).permitAll()
.and()
.httpBasic()
.and()
.csrf().disable();
}
【问题讨论】:
标签: spring spring-mvc spring-boot spring-security spring-data