【问题标题】:MockUser required for endpoint without authentication requirement没有身份验证要求的端点需要 MockUser
【发布时间】:2020-03-20 18:09:29
【问题描述】:

我的SecurityConfiguration配置如下:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and()
            .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
            .authorizeRequests()
            .antMatchers("/api/auth", "/api/auth/**", "/api/oauth2/**").permitAll()
            .anyRequest().authenticated().and()
            .oauth2Login()
            //
}

我正在测试我的自定义身份验证 POST 端点 /api/auth/login/api/auth/register。该应用程序运行良好,我目前正在为它们追溯编写单元测试。在我的控制器单元测试中,我有以下内容:

@WebMvcTest(AuthenticationController.class)
@ContextConfiguration(classes = {AuthenticationController.class})
class AuthenticationControllerTest {

@Test
void register() throws Exception {
    mockMvc.perform(post(BASE_PATH + "/register")
        .content(...) // POST body
        .with(csrf()))
        .andExpect(status().isOk());
}

这会返回 HTTP 401 (Unauthorized) 而不是预期的 HTTP 200。但是如果我将 @WithMockUser(不带任何参数)添加到测试方法中,那么它确实会返回 200。为什么需要模拟用户,因为我不需要在 /api/auth 端点上进行身份验证? 可以肯定的是,我尝试在 SecurityConfiguration 中设置 /api/auth/**,但同样的问题仍然存在。我还没有实现任何与授权相关的东西,所以角色不是问题。

编辑:值得注意的是,我也尝试设置.anyRequest().permitAll(),本质上是说我的所有端点都不需要身份验证,但会出现同样的问题。

EDIT2:更新了测试 sn-p,我使用了以下依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

【问题讨论】:

  • 您能否添加您的整个测试以查看您在测试执行期间如何引导以及引导哪些部分?如果您使用 Spring Boot Starter for Security 或 Spring Security,还请添加您的pom.xml 或提供更多信息
  • @rieckpil 我已将您要求的信息添加到我的问题中

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


【解决方案1】:

从这篇帖子SpringBoot @WebMvcTest security issue 我了解到SecurityConfiguration 默认不导入。这就解释了为什么修改配置没有影响。如果应该加载 SecurityConfiguration 我需要添加 @Import(SecurityConfiguration.class) 并提供它看起来的 bean 依赖项。

我相信它更适合 e2e 测试,所以我没有将它添加到我的单元测试中。

简单地将@WithMockUser 添加到每个测试方法的另一种方法是将@AutoConfigureMockMvc(addFilters = false) 添加到类中。这将禁用安全过滤器。

【讨论】:

    猜你喜欢
    • 2015-05-14
    • 2018-06-20
    • 2022-01-12
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多