在Spring Boot 1.4中测试安全性

8

我正在尝试使用在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类中定义的设置?

只需将以下内容添加到“application.properties”(位于“src/main/resources”中)即可:security.user.password=password(并选择您自己的密码) - AchillesVan
1
谢谢,但不要修复它...仍然使用默认安全设置,但强制密码为“password”。我只是使用角色“ADMIN”来保护“/admin*” URI, 默认安全配置使用角色“USER”来保护所有URI。 - dmunozfer
谢谢你的评论,David。我不知道默认安全性会保护所有URI使用USER - Snekse
1个回答

11

WebMvcTest只会加载你的控制器,不会加载其他任何内容(这就是我们所谓的切片)。我们无法确定您想要哪些配置和不需要哪些配置。如果安全配置不在您的主要@SpringBootApplication中,则必须显式导入它。否则,Spring Boot将启用默认安全设置。

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


3
请注意:Spring Boot的问题跟踪器中也有相关讨论:https://github.com/spring-projects/spring-boot/issues/6514 - Sam Brannen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接