【问题标题】:Mock JwtDecoder in Spring Security在 Spring Security 中模拟 JwtDecoder
【发布时间】:2021-06-15 19:57:09
【问题描述】:

这是我的服务类方法中的代码,用于根据传递的身份验证令牌获取 JWT 令牌。

        NimbusJwtDecoder decoder = (NimbusJwtDecoder) JwtDecoders.fromOidcIssuerLocation(userTokenUrl);
        Jwt jwt = decoder.decode(authResponse.authenticationResult().idToken());
        Map<String, Object> claims = jwt.getClaims();
        if(!ACTIVE.equals(claims.get(CUSTOM_STATUS).toString())) {
            throw new IllegalArgumentException("User is not active");
        }

我想为这个服务类方法写一个 JUnit。下面的方法我尝试过,但在尝试解码令牌 id 时出错 IllegalArgumentException:尝试解码 Jwt 时发生错误:签名的 JWT 被拒绝:需要另一个算法,或找不到匹配的密钥

    NimbusJwtDecoder decoder = mock(NimbusJwtDecoder.class);
    when(decoder.decode(ArgumentMatchers.anyString()))
            .thenReturn(Jwt.withTokenValue(getToken()).header("typ", "JWT").header("alg", "HS256").claim("custom:status", "active").build());

【问题讨论】:

  • 您采用了错误的方法,您的“业务代码”不应该知道您使用什么来保护您的应用程序。只有“安全功能”需要处理它,并在验证后将其转换为内部标准用户信息,您可以在其余代码中使用。这样,您将能够使用@WithMockUser 和类似的注释来编写您的测试。 Spring 提供了很多功能来帮助您,并且有几个在线教程可以知道如何做到这一点。

标签: spring spring-boot junit spring-security spring-test


【解决方案1】:

我不确定这是可行的解决方案,但这对我有用。我通过提取我的 jwt 解码器代码来重构我的代码。我创建了一个返回 Jwt 对象的新方法。

public Jwt getJwt(InitiateAuthResponse authResponse) {
    NimbusJwtDecoder decoder = (NimbusJwtDecoder) JwtDecoders.fromOidcIssuerLocation(userTokenUrl);
    return decoder.decode(authResponse.authenticationResult().idToken());
}

我在我的测试类中模拟这个方法。

    Map<String, Object> headers = new HashMap<>();
    headers.put(HttpHeaders.AUTHORIZATION, "Bearer token");
    headers.put("typ", "JWT");
    headers.put("alg", "none");

    Map<String, Object> claims = new HashMap<>();
    claims.put("custom:status", "active");
    
    Jwt jwt = new Jwt("fake-token", Instant.now(), Instant.now().plusSeconds(100), headers, claims);
    doReturn(jwt).when(spyService).getJwt(ArgumentMatchers.any());

【讨论】:

    猜你喜欢
    • 2020-03-04
    • 2011-09-14
    • 2012-08-09
    • 2013-02-18
    • 2017-07-30
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多