WebSphere Liberty - JWT - 无法注入 JsonWebToken Principal,因为一个不可用

WebSphere Liberty - JWT - A JsonWebToken Principal can't be injected because one is not available

我正在尝试在 WebSphere Liberty 上实施 JWT,但是在授权 header 中传递 JWT 时 运行 出错了。

无法注入 JsonWebToken Principal,因为一个不可用。保护请求资源,以便在访问资源之前进行身份验证。

同一个 JWT 是用私钥签名的,可以使用 public 密钥或 public 证书在 jwt.io 上成功验证,所以我认为有效性不是问题.

这是我将 JWT 传递到的 JAXRS 网络资源:

import org.eclipse.microprofile.jwt.Claim;
import org.eclipse.microprofile.jwt.Claims;
import org.eclipse.microprofile.jwt.JsonWebToken;
import javax.annotation.security.PermitAll;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

@Path("/jwtpoc")
@PermitAll
@RequestScoped
public class JwtPocResource {
    @Inject
    @Claim(standard = Claims.groups)
    private Set<String> groups;

    @Inject
    private JsonWebToken token;

    @GET
    public Response getOK() {
        return Response.ok().build();
    }
}

请求 GET /jwtpoc 时,我可以看到“无法注入 JsonWebToken Principal,因为一个不可用。保护请求资源,以便在访问资源之前进行身份验证。”在 messages.log 所以我认为这是一些注入或底层配置的问题。

我将我的密钥对设置为 pkcs#12 密钥库,public 证书存储在 pkcs#12 信任库中,两者都由 ssl 配置引用,并且对 ssl 配置的引用在 mpJwt server.xml元素。我正在使用 microprofile 3.2 (mpjwt-1.1)。

引用 JwtPocResource 的应用程序 class 具有:

import org.eclipse.microprofile.auth.LoginConfig;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;

@LoginConfig(authMethod = "MP-JWT")
@ApplicationPath("/")
public class JwtPocApplication extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> services = new HashSet<Class<?>>();
        services.add(JwtPocResource.class);
    }
}

有没有人以前见过这个并且可以提出解决方案?

为了进行注入,必须保护资源。根据 https://download.eclipse.org/microprofile/microprofile-jwt-auth-1.2/microprofile-jwt-auth-spec-1.2.html#_injection_of_code_jsonwebtoken_code,注入是为经过身份验证的调用者完成的。

对 JAXRS 使用 @PermitAll 会将此资源视为不受保护的资源,并且不会有经过身份验证的调用者,并且不会发生 JsonWebToken 的注入。

要解决这个问题,可以使用@RolesAllowed 来保护资源。

如果端点必须使用@PermitAll 来处理自己的身份验证和授权,则适用以下内容,

If a JWT is sent to an endpoint that does not require Authentication and/or Authorization then it still must be verified before it can be accessed via JsonWebToken interface.

Endpoints which need to control the authentication process themselves can check if a token is available by calling a JsonWebToken.getRawToken() method.

对于 1.1,身份验证要求也适用 https://download.eclipse.org/microprofile/microprofile-jwt-auth-1.1/microprofile-jwt-auth-spec.html#_injection_of_code_jsonwebtoken_code

An MP-JWT implementation must support the injection of the currently authenticated caller as a JsonWebToken