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

标签 java spring spring-security spring-boot spring-test-mvc

我正在尝试使用 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", 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 来解决这个问题,但是在不运行所有自动配置的情况下进行测试会很有趣。

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class ExampleControllerSpringBootTest {

    @Autowired
    private MockMvc mockMvc;

    // tests
}

@WebMvcTest 是否可以使用 SecurityConfig 类中定义的设置?

最佳答案

WebMvcTest 只会加载您的 Controller ,不会加载其他任何东西(这就是我们称之为切片的原因)。我们无法弄清楚您想要配置的哪一部分以及不需要哪一部分。如果安全配置不在您的主 @SpringBootApplication 上,您必须显式导入它。否则,Spring Boot 将启用默认安全设置。

如果您使用 OAuth 之类的东西,那是一件好事,因为您真的不想开始使用它进行模拟测试。如果将 @Import(SecurityConfig.class) 添加到测试中会发生什么情况?

关于java - 在 Spring Boot 1.4 中测试安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38675020/

相关文章:

java - Wicket validator 不会对空字段值引发错误

java - JCheckBox在其他类中设置值

java - 无法配置 Unirest 请求正文

java - Aspectj 没有捕获 spring 框架中的所有事件?

java - 每层集成测试是一个好习惯吗?

java - 无法使用 @springboot.web.CommentsApiControllerTest$WithMockCustomUser 创建 SecurityContext

java - 这些初始化 HashMap 的方式有什么区别?

java - org.openqa.selenium.WebDriverException : Timed out waiting for driver server to start. 构建信息 : version: 'unknown' , 修订版: 'unknown'

spring-security - 如何在 Vaadin 中注销 Spring Security?

java - session 验证 - Spring Security with Microservices