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

Payara Micro中JWT令牌无法用于授权的问题排查

问题

按照Payara官方文档配置了OpenID Connect认证与授权功能,但在请求头中携带Authorization: Bearer ey...格式的JWT令牌调用应用时,请求失败并被重定向至认证页面。

配置的Application类代码:

@ApplicationPath("/")
@OpenIdAuthenticationDefinition(
        providerURI = "https://my-idp.com/auth",
        clientId = "my-app-id",
        clientSecret = "my-app-secret",
        redirectURI = "http://localhost:8080/myapp/oauth2/callback",
        scope = "openid"
)
@DeclareRoles({"my_role"})
public class MyApp extends Application {

}

资源类代码:

@Path("/my")
@RequestScoped
public class TestResource {

    @Context
    SecurityContext securityContext;

    @GET
    @Path("resource")
    @Produces(MediaType.TEXT_PLAIN)
    @RolesAllowed("my_role")
    public String getName() {
        return securityContext.getUserPrincipal().getName();
    }
}

请问这是否意味着Payara Micro不支持该功能?如果是,为何授权部分可以正常工作?

回答

Payara Micro是支持通过Authorization头携带Bearer JWT令牌进行认证的,你遇到的问题是因为默认配置只启用了基于重定向的授权码流,没有开启直接处理请求中JWT的模式。

  • 默认的@OpenIdAuthenticationDefinition配置仅针对交互式登录场景(用户跳转IDP登录后获取令牌的流程),所以你看到授权部分(登录后访问资源)能正常工作,但直接传入Bearer令牌的非交互式请求不会被处理,会被重定向到认证页面。
  • 要解决这个问题,需要在@OpenIdAuthenticationDefinition中添加useJWTFromRequest = UseJWTFromRequest.ALWAYS属性,明确指定Payara优先从请求头中提取并验证JWT令牌:

修改后的Application类代码:

@ApplicationPath("/")
@OpenIdAuthenticationDefinition(
        providerURI = "https://my-idp.com/auth",
        clientId = "my-app-id",
        clientSecret = "my-app-secret",
        redirectURI = "http://localhost:8080/myapp/oauth2/callback",
        scope = "openid",
        useJWTFromRequest = UseJWTFromRequest.ALWAYS
)
@DeclareRoles({"my_role"})
public class MyApp extends Application {

}
  • 另外需要确认:IDP签发的JWT中包含了正确的角色声明(通常是groups字段,或者需要通过groupClaimName属性指定自定义声明名),确保my_role能被正确映射到用户的角色列表中,否则即使令牌验证通过,@RolesAllowed注解也会拒绝请求。
  • 检查JWT的有效性:确保令牌未过期、签名算法与IDP配置一致,Payara能通过IDP的公开密钥验证令牌签名。

内容的提问来源于stack exchange,提问作者FourtyTwo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:22:55