Tôi đang cố gắng để kiểm tra @WebMvcTest
với các thiết lập bảo mật tuỳ chỉnh theo quy định tại SecurityConfig
lớp:kiểm tra an ninh trong mùa xuân Boot 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");
}
}
class Test là:
@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")));
}
}
thử nghiệm thất bại bởi vì họ đang sử dụng cài đặt bảo mật mặc định của Spring Boot.
Tôi có thể sửa lỗi này bằng cách sử dụng @SpringBootTest
+ @AutoConfigureMockMvc
, nhưng sẽ rất thú vị khi thử nghiệm mà không cần chạy tất cả cấu hình tự động.
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class ExampleControllerSpringBootTest {
@Autowired
private MockMvc mockMvc;
// tests
}
Có cách nào mà @WebMvcTest
có thể sử dụng các thiết lập quy định tại SecurityConfig
lớp học?
chỉ cần thêm mục này vào "application.properties" (trong "src/main/resources"): security.user.password = mật khẩu (và chọn mật khẩu của riêng bạn) –
Cảm ơn nhưng đừng sửa nó ... vẫn bằng cách sử dụng cài đặt bảo mật mặc định nhưng buộc phải đặt mật khẩu thành "mật khẩu". Tôi chỉ bảo vệ các URI "/ admin *" bằng vai trò "ADMIN", cấu hình bảo mật mặc định bảo vệ tất cả các URI bằng vai trò "USER". – dmunozfer
Cảm ơn lời bình luận David. Tôi không biết về bảo mật mặc định bảo vệ tất cả các URI bằng 'USER'. – Snekse