【发布时间】: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