我有一个WebSecurityConfigurerAdapter的自定义实现,其中我重写config()方法以授权具有匹配器的请求。
我需要创建使用模拟mvc的单元测试,以将请求发送到 Controller ,以确保它们被正确阻止。但是,当我运行测试时,它们不会加载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();
}
这是我的单元测试:
@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();
}
}
该测试的结果应该是服务器发出的403,但仍然是200 ... :(
最佳答案
您需要为 mock Mvc添加安全性:
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity())
.build();
例如,看看https://github.com/spring-projects/spring-security/blob/master/test/src/test/java/org/springframework/security/test/web/servlet/showcase/secured/SecurityRequestsTests.java