首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Spring Boot 1.4中测试安全性

在Spring Boot 1.4中测试安全性
EN

Stack Overflow用户
提问于 2016-07-30 22:29:52
回答 1查看 9K关注 0票数 6

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

代码语言:javascript
复制
@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");
    }
}

测试类为:

代码语言:javascript
复制
@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", password="password", 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来修复这个问题,但是在不运行所有自动配置的情况下进行测试会很有趣。

代码语言:javascript
复制
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class ExampleControllerSpringBootTest {

    @Autowired
    private MockMvc mockMvc;

    // tests
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-31 00:35:17

WebMvcTest只会加载你的控制器,而不会加载其他东西(这就是我们称之为切片的原因)。我们无法确定您需要哪部分配置,哪部分不需要。如果安全配置不在您的主@SpringBootApplication上,则必须显式导入。否则,Spring Boot将启用默认安全设置。

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

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38675020

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档