如何在Quarkus自定义JWTCallerPrincipalFactory子类中获取请求头?
在Quarkus自定义JWTCallerPrincipalFactory中获取请求头的可行方法
有两种可靠的实现方式,具体如下:
方法一:通过CurrentRequest注入获取请求头
- 在自定义的
JWTCallerPrincipalFactory子类中,注入io.quarkus.vertx.http.runtime.CurrentRequest实例:import io.quarkus.vertx.http.runtime.CurrentRequest; import io.smallrye.jwt.auth.principal.JWTCallerPrincipal; import io.smallrye.jwt.auth.principal.JWTCallerPrincipalFactory; import io.smallrye.jwt.auth.principal.ParseException; import io.smallrye.jwt.auth.principal.JWTAuthContextInfo; import jakarta.inject.Inject; public class CustomJWTCallerPrincipalFactory extends JWTCallerPrincipalFactory { @Inject CurrentRequest currentRequest; @Override public JWTCallerPrincipal parse(String token, JWTAuthContextInfo authContextInfo) throws ParseException { // 按需获取指定请求头 String customHeader = currentRequest.get().request().getHeader("X-Custom-Header"); // 执行自定义业务逻辑 return super.parse(token, authContextInfo); } } - 在
application.properties中配置自定义工厂类路径:smallrye.jwt.principal-factory=com.your.package.CustomJWTCallerPrincipalFactory
方法二:利用VertxRequestContext获取请求上下文
若CurrentRequest无法满足需求,可通过io.quarkus.vertx.core.runtime.VertxRequestContext直接获取请求上下文:
import io.quarkus.vertx.core.runtime.VertxRequestContext; import io.smallrye.jwt.auth.principal.JWTCallerPrincipal; import io.smallrye.jwt.auth.principal.JWTCallerPrincipalFactory; import io.smallrye.jwt.auth.principal.ParseException; import io.smallrye.jwt.auth.principal.JWTAuthContextInfo; public class CustomJWTCallerPrincipalFactory extends JWTCallerPrincipalFactory { @Override public JWTCallerPrincipal parse(String token, JWTAuthContextInfo authContextInfo) throws ParseException { VertxRequestContext requestContext = VertxRequestContext.current(); if (requestContext != null) { String authHeader = requestContext.request().getHeader("Authorization"); // 处理获取到的请求头数据 } return super.parse(token, authContextInfo); } }
注意事项
- 两种方式均依赖Quarkus的Vertx HTTP上下文,需确保代码运行在请求处理的Vertx线程中,异步线程中调用可能导致
current()返回null。 - 禁止在工厂类的构造方法中尝试获取请求头,此时依赖注入未完成,会触发空指针异常。
内容的提问来源于stack exchange,提问作者680ca2
相关产品推荐
相关产品推荐

