加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:48:58 所属栏目:大数据 来源:网络整理
导读:我正在尝试使用SecurityConfig类中定义的自定义安全设置来测试@WebMvcTest: @Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Excepti

我正在尝试使用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)添加到测试中会发生什么?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读