bra*_*ran 7 java spring unit-testing
我有一个 WebSecurityConfigurerAdapter 的自定义实现,我在其中覆盖了 config() 方法以使用匹配器授权请求。
我需要创建使用模拟 mvc 向我的控制器发送请求的单元测试,以确保它们被正确阻止。但是当我运行测试时,它们不会加载我对 WebSecurityConfigurerAdapter 的实现。
从我的SecurityConfigSso.class覆盖 WebSecurityConfigurerAdapter::configure() 方法:
@Override
protected void configure( HttpSecurity http ) throws Exception {
http.authorizeRequests()
.antMatchers( "/img/**", "lib/**", "/api/event**", "/api/event/**","/login/cas**" ).permitAll()
.antMatchers(HttpMethod.GET, "/**").hasAnyAuthority(AvailableRoles.ANY)
.antMatchers(HttpMethod.POST, "/**").hasAnyAuthority(AvailableRoles.ADMIN, AvailableRoles.GIS_ANALYST)
.antMatchers(HttpMethod.PUT, "/**").hasAnyAuthority(AvailableRoles.ADMIN, AvailableRoles.GIS_ANALYST)
.antMatchers(HttpMethod.DELETE, "/**").hasAnyAuthority(AvailableRoles.ADMIN, AvailableRoles.GIS_ANALYST)
.anyRequest().authenticated();
}
Run Code Online (Sandbox Code Playgroud)
这是我的单元测试:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { SecurityConfigSso.class })
public class SecurityTestControllerTests {
private final String SECURITY_URL = "/security";
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@Before
public void init() {
Assert.assertNotNull(context);
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void postMethodShouldBeForbiddenToGuest() throws Exception {
this.mockMvc.perform(post(SECURITY_URL).with(user("test").roles(AvailableRoles.GUEST)))
.andExpect(status().isForbidden()).andReturn();
}
}
Run Code Online (Sandbox Code Playgroud)
这个测试的结果应该是来自服务器的 403,但它仍然是 200... :(
您需要为mockMvc 添加安全性:
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity())
.build();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3879 次 |
| 最近记录: |