我試圖測試@WebMvcTest
與SecurityConfig
類中定義自定義安全設置:測試安全1.4
@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。 – dmunozfer
感謝您的評論大衛。我沒有意識到默認安全保護所有的URI都是用'USER'。 – Snekse