自定义HttpAuthenticationMechanism后@TestSecurity测试失败
解决自定义HttpAuthenticationMechanism导致@TestSecurity注解失效的问题
方案一:限制自定义认证机制仅在非测试环境生效
给你的MyHttpAuthenticationMechanism添加@Profile注解,指定它只在非测试环境激活。测试时Quarkus会自动使用默认的JWT认证机制,@TestSecurity就能正常注入测试身份:
@Alternative @Priority(1) @ApplicationScoped @Profile("!test") // 仅在非test环境生效 public class MyHttpAuthenticationMechanism implements HttpAuthenticationMechanism { @Inject JWTAuthMechanism jwt; @Override public Uni<SecurityIdentity> authenticate(RoutingContext context, IdentityProviderManager identityProviderManager) { return jwt.authenticate(context, identityProviderManager); } @Override public Uni<ChallengeData> getChallenge(RoutingContext context) { return jwt.getChallenge(context); } @Override public Set<Class<? extends AuthenticationRequest>> getCredentialTypes() { return jwt.getCredentialTypes(); } @Override public Uni<HttpCredentialTransport> getCredentialTransport(RoutingContext context) { return jwt.getCredentialTransport(context); } }
方案二:在自定义机制中兼容测试身份注入
如果需要自定义机制在测试环境也生效,可以修改authenticate方法,先检查上下文是否存在@TestSecurity注入的测试身份,存在则直接返回,否则再执行JWT认证逻辑:
@Alternative @Priority(1) @ApplicationScoped public class MyHttpAuthenticationMechanism implements HttpAuthenticationMechanism { @Inject JWTAuthMechanism jwt; @Override public Uni<SecurityIdentity> authenticate(RoutingContext context, IdentityProviderManager identityProviderManager) { // 检查是否存在测试注入的SecurityIdentity SecurityIdentity testIdentity = context.get(SecurityIdentity.class); if (testIdentity != null) { return Uni.createFrom().item(testIdentity); } // 否则执行JWT认证 return jwt.authenticate(context, identityProviderManager); } @Override public Uni<ChallengeData> getChallenge(RoutingContext context) { return jwt.getChallenge(context); } @Override public Set<Class<? extends AuthenticationRequest>> getCredentialTypes() { return jwt.getCredentialTypes(); } @Override public Uni<HttpCredentialTransport> getCredentialTransport(RoutingContext context) { return jwt.getCredentialTransport(context); } }
内容的提问来源于stack exchange,提问作者abeggchr
相关产品推荐
相关产品推荐

