微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 在Spring Boot 1.4中测试安全性

我正在尝试使用SecurityConfig类中定义的自定义安全设置来测试@WebMvcTest:

@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");
    }
}

测试类是:

@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",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")));
    }
}

测试失败,因为他们使用Spring Boot的认安全设置.

我可以使用@SpringBoottest @AutoConfiguremockmvc解决这个问题,但是在不运行所有自动配置的情况下进行测试会很有趣.

@RunWith(springrunner.class)
@SpringBoottest(webEnvironment = WebEnvironment.MOCK)
@AutoConfiguremockmvc
public class ExampleControllerSpringBoottest {

    @Autowired
    private mockmvc mockmvc;

    // tests
}

有没有办法让@WebMvcTest可以使用SecurityConfig类中定义的设置?

最佳答案
WebMvcTest只会加载你的控制器而没有别的东西(这就是我们称之为切片的原因).我们无法确定您想要的配置部分以及您不需要的部分.如果安全配置不在主@SpringBootApplication上,则必须明确导入它.否则,Spring Boot将启用认安全设置.

如果你正在使用像OAuth这样的东西,这是一件好事,因为你真的不想开始使用它进行模拟测试.如果将@Import(SecurityConfig.class)添加到测试中会发生什么?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐