繁体   English   中英

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

[英]How to use Spring MockMVC with custom Spring Security WebSecurityConfigurerAdapter

我有一个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();
}

这是我的单元测试:

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

您需要为mockMvc添加安全性:

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/安全/ SecurityRequestsTests.java

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM