首页 > 解决方案 > 为什么 Quarkus JWT 在每个端点上都未经授权返回

问题描述

我正在尝试使用 JWT 保护我的 Quarkus API。提供了 JWT(片段:)Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUI[...]

以下端点是我测试过的 2 个端点:

@Path("/quiz")
@RequestScoped
public class SomeResource {
  @Inject
  JsonWebToken jwt;

  @POST
  @RolesAllowed({"magister"})
  @Path("/save")
  @Consumes("application/json")
  @Produces("*/*")
  @Transactional
  public Response save(@RequestBody Quiz quiz) { }

  @GET
  @PermitAll
  @Path("/get/all")
  @Produces("application/json")
  public Response getAll(){ }

两个端点(@PermitAll@RolesAllowed)都返回给我一个 HTTP 401(未经授权)。

你知道为什么吗?我认为这@PermitAll是允许每个请求?即使我的令牌证明我具有所需的角色:

"resource_access" : {
  "client_interface" : {
    "roles" : ["magister"]
  },
  ...
}

编辑:发现 MicroProfile 规范说

"groups":["magister"]

应该通过微配置文件映射到 RolesAllowed 注释。

我的有效负载看起来像这样:

{
  [...]
  "resource_access": {
    "client_interface": {
      "roles": [
        "magister"
      ]
    },
    "account": {
      "roles": [
        "manage-account",
        "manage-account-links",
        "view-profile"
      ]
    }
  },
  "scope": "profile email",
  "email_verified": false,
  "groups": [
    "magister"
  ],
  "preferred_username": "magister"
}

但我仍然会收到 401 响应

标签: jwtquarkusmicroprofile

解决方案


我遇到了同样的问题,我通过添加以下代码来解决它:

@OpenAPIDefinition(
        info = @Info(
                title = "Title API",
                version = "1.0.0",
                description = "Description API"
        ),
        security = @SecurityRequirement(name = "jwt"),
        components = @Components(
                securitySchemes = {
                        @SecurityScheme(
                                securitySchemeName = "jwt",
                                description = "Token JWT",
                                type = SecuritySchemeType.HTTP,
                                scheme = "bearer",
                                bearerFormat = "jwt"
                        )
                }
        )
)

并且还更新了 Quarkus 到 1.12.0.FINAL 版本


推荐阅读