You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 03:55:21