【问题标题】:Failed to load ApplicationContext with OAuth2 resource server issuer URI when running @WebMvcTest运行 @WebMvcTest 时无法使用 OAuth2 资源服务器颁发者 URI 加载 ApplicationContext
【发布时间】:2022-06-24 01:48:54
【问题描述】:

我的 Spring Boot 应用程序在 application.yml 中定义了一个像这样的 OAuth2 资源服务器:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: ${AUTH_SERVER_METADATA_URL:http://localhost:8080/auth/realms/demo}

这在实际运行应用程序时工作正常。

但是,当使用@WebMvcTestMockMvc 运行测试来测试@RestController 类时,测试会失败并出现以下错误:

java.lang.IllegalStateException: Failed to load ApplicationContext
...
...
...
I/O error on GET request for "http://localhost:8080/auth/realms/demo/.well-known/openid-configuration": Connection refused (Connection refused); nested exception is java.net.ConnectException: Connection refused (Connection refused)

消息的根本原因很清楚,但我不知道如何在不启动真正的 Keycloak 或 WireMock 服务器的情况下“模拟”切片测试的连接。

在后台运行我的开发 Keycloak 服务器运行相同的测试工作正常。

【问题讨论】:

标签: spring spring-boot spring-security


【解决方案1】:

您是否尝试将@MockBean JwtDecoder 添加到您的单元测试类属性中?

接下来您可能需要使用满足您的安全规则的JwtAuthenticationToken 实例填充您的安全上下文。

为此,您可以使用:

两者都在行动:

@WebMvcTest(GreetingController.class)
@Import(SampleApi.WebSecurityConfig.class)
class GreetingControllerAnnotatedTest {

    @MockBean JwtDecoder jwtDecoder;

    @Autowired
    MockMvc api;

    @Test
    @WithMockJwtAuth(authorities = "ROLE_AUTHORIZED_PERSONNEL", claims = @OpenIdClaims(sub = "Ch4mpy", preferredUsername = "Tonton Pirate"))
    void greetWithAnnotation() throws Exception {
        api.perform(get("/greet")).andExpect(content().string("Hello Ch4mpy! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."));
    }

    @Test
    void greetWithPostProcessor() throws Exception {
        api.perform(get("/greet").with(SecurityMockMvcRequestPostProcessors.jwt()
                .authorities(List.of(new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL"))).jwt(jwt -> {
                    jwt.subject("Ch4mpy");
                    jwt.claims(claims -> claims.put(StandardClaimNames.PREFERRED_USERNAME, "Tonton Pirate"));
                }))).andExpect(content().string("Hello Ch4mpy! You are granted with [ROLE_AUTHORIZED_PERSONNEL]."));
    }
}

完整示例there

【讨论】:

    猜你喜欢
    • 2020-03-14
    • 2021-07-14
    • 1970-01-01
    • 2018-06-13
    • 2019-06-09
    • 1970-01-01
    • 2019-12-29
    • 2017-10-06
    • 2020-10-16
    相关资源
    最近更新 更多