[英]Testing security in Spring Boot 1.4
我正在嘗試使用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
修復此@AutoConfigureMockMvc
,但是在不運行所有自動配置的情況下進行測試將很有趣。
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class ExampleControllerSpringBootTest {
@Autowired
private MockMvc mockMvc;
// tests
}
@WebMvcTest
有什么方法可以使用SecurityConfig
類中定義的設置嗎?
WebMvcTest
只會加載您的控制器,而不會加載任何其他內容(這就是我們稱其為切片的原因)。 我們無法確定您需要配置的哪一部分,而不需要。 如果安全配置不在主@SpringBootApplication
,則必須顯式導入它。 否則,Spring Boot將啟用默認安全設置。
如果您使用的是OAuth之類的東西,那是一件好事,因為您真的不想開始將其用於模擬測試。 如果將@Import(SecurityConfig.class)
添加到測試中會怎樣?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.