SpringBootWebMVCTest返回302而不是401作为get方法

mu0hgdu0  于 2021-09-30  发布在  Java
关注(0)|答案(1)|浏览(370)

我有一个应用程序,其rest端点由 JWT 身份验证(外部资源服务器)。将我的项目从SpringBoot2.2.7升级到2.4.3之后 WebMvcTest 集成测试失败了。具体来说,测试用例 GET 未经批准的请求 JWT 代币-以前它们会返回 401 UNAUTHORIZED ,现在他们回来了 302 REDIRECThttp://localhost/oauth2/authorization/keycloak .

@Test
void shouldNotAllowAccessForUnauthenticatedUsers() throws Exception {
    // given
    var params = createParams();

    // when / then
    mockMvc.perform(get(MY_URI)
            .params(params)
            .contentType(MediaType.APPLICATION_JSON)
            .content(new byte[0]))
            .andExpect(status().isUnauthorized());
}

没有导入自定义的web安全配置,只是 @WebMvcTest , @AutoConfigureMockMvc 加上 @ContextConfiguration 用于相关控制器和Map器bean。 POST 测试中没有身份验证返回的方法 403 (与升级之前一样)。此问题仅在测试中发生-当应用程序正在运行时,调用任何没有令牌的端点都会导致错误 401 .
有没有一种配置方法 WebMvcTest 归来 401 而不是 302 ?

ltqd579y

ltqd579y1#

andy wilkinson的问题激发了我对这一点的深入研究,因为没有真正添加KeyClope适配器作为显式依赖项(仅限于 spring-boot-starter-security , spring-boot-starter-oauth2-client , spring-boot-starter-oauth2-resource-server ),但是 keycloak 在这里的配置中提到:

security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: ...
      client:
        registration:
          keycloak:
            client-id: ...
            client-secret: ...
            authorization-grant-type: ...
            scope: ...
        provider:
          keycloak:
            authorization-uri: ...
            token-uri: ...

对应用程序端点的请求使用来自颁发者uri的jwt令牌进行身份验证,但对其他服务的http客户端调用使用KeyClope中的客户端注册进行身份验证(用于服务到服务身份验证)。
无论如何,我相信升级后的这种行为变化是由于SpringBoot2.3中引入了一个特性,特别是:“中的oauth2参数绑定” @WebMvcTest ". oauth2的自动配置现在包含在 @WebMvcTest 这导致此测试尝试使用客户端配置重定向到Key斗篷(在运行时仅用于服务到服务)。
我通过使用以下注解测试类修复了该问题:

@ImportAutoConfiguration(exclude = {OAuth2ClientAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class})

(为了正确处理模拟jwt,还必须排除资源服务器配置。)
也许有人会觉得这很有帮助。

相关问题