如何将 Spring MockMVC 与自定义 Spring Security WebSecurityConfigurerAdapter 一起使用

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... :(

Jef*_*f E 4

您需要为mockMvc 添加安全性:

mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity())
.build();
Run Code Online (Sandbox Code Playgroud)

例如,请查看https://github.com/spring-projects/spring-security/blob/master/test/src/test/java/org/springframework/security/test/web/servlet/showcase/安全/SecurityRequestsTests.java