【发布时间】:2016-12-05 03:03:30
【问题描述】:
我正在尝试使用在 SecurityConfig 类中定义的自定义安全设置来测试 @WebMvcTest:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin*").access("hasRole('ADMIN')").antMatchers("/**").permitAll().and().formLogin();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("ADMIN");
}
}
测试类是:
@RunWith(SpringRunner.class)
@WebMvcTest(value = ExampleController.class)
public class ExampleControllerMockMVCTest {
@Autowired
private MockMvc mockMvc;
@Test
public void indexTest() throws Exception {
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("index"));
}
@Test
public void adminTestWithoutAuthentication() throws Exception {
mockMvc.perform(get("/admin"))
.andExpect(status().is3xxRedirection()); //login form redirect
}
@Test
@WithMockUser(username="example", password="password", roles={"ANONYMOUS"})
public void adminTestWithBadAuthentication() throws Exception {
mockMvc.perform(get("/admin"))
.andExpect(status().isForbidden());
}
@Test
@WithMockUser(username="user", password="password", roles={"ADMIN"})
public void adminTestWithAuthentication() throws Exception {
mockMvc.perform(get("/admin"))
.andExpect(status().isOk())
.andExpect(view().name("admin"))
.andExpect(model().attributeExists("name"))
.andExpect(model().attribute("name", is("user")));
}
}
测试失败,因为它们使用的是 Spring Boot 的默认安全设置。
我可以使用@SpringBootTest + @AutoConfigureMockMvc 解决此问题,但如果不运行所有自动配置进行测试会很有趣。
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class ExampleControllerSpringBootTest {
@Autowired
private MockMvc mockMvc;
// tests
}
@WebMvcTest 是否可以使用SecurityConfig 类中定义的设置?
【问题讨论】:
-
只需将其添加到“application.properties”(在“src/main/resources”中):security.user.password=password(并选择您自己的密码)
-
谢谢,但不要修复它...仍然使用默认安全设置,但强制密码为“密码”。我只是使用角色“ADMIN”保护“/admin*”URI,默认安全配置使用角色“USER”保护所有 URI。
-
感谢大卫的评论。我不知道使用
USER保护所有 URI 的默认安全性。
标签: java spring spring-security spring-boot spring-test-mvc