0

我想使用 Jose4j 将 JWT 的主体提取为 JSON。这可能吗?

我们需要支持自定义验证,该验证可以任意简单或非常复杂,具体取决于客户。我们需要 JSON 形式的主体,以便我们可以将其作为参数传递给客户特定的 Javascript 方法。

4

1 回答 1

1

调用从中获得getRawJson()JwtClaims对象JwtConsumer将为您提供 JWT 的 JSON 有效负载,这听起来就像您正在寻找的那样。

以下来自https://bitbucket.org/b_c/jose4j/wiki/JWT%20Examples的代码片段稍作修改以显示getRawJson()正在使用。

    // Use JwtConsumerBuilder to construct an appropriate JwtConsumer, which will
    // be used to validate and process the JWT.
    // The specific validation requirements for a JWT are context dependent, however,
    // it typically advisable to require a (reasonable) expiration time, a trusted issuer, and
    // and audience that identifies your system as the intended recipient.
    // If the JWT is encrypted too, you need only provide a decryption key or
    // decryption key resolver to the builder.
    JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setRequireExpirationTime() // the JWT must have an expiration time
            .setRequireSubject() // the JWT must have a subject claim
            .setExpectedIssuer("Issuer") // whom the JWT needs to have been issued by
            .setExpectedAudience("Audience") // to whom the JWT is intended for
            .setVerificationKey(rsaJsonWebKey.getKey()) // verify the signature with the public key
            .setJwsAlgorithmConstraints( // only allow the expected signature algorithm(s) in the given context
                    ConstraintType.PERMIT, AlgorithmIdentifiers.RSA_USING_SHA256) // which is only RS256 here
            .build(); // create the JwtConsumer instance

    try
    {
        //  Validate the JWT and process it to the Claims
        JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
        System.out.println("JWT validation succeeded! " + jwtClaims);

        String jsonPayload = jwtClaims.getRawJson();
        System.out.println("JWT's JSON payload: " + jsonPayload);

    }
    catch (InvalidJwtException e)
    {
        // InvalidJwtException will be thrown, if the JWT failed processing or validation in anyway.
        // Hopefully with meaningful explanations(s) about what went wrong.
        System.out.println("Invalid JWT! " + e);
    }

于 2021-03-04T13:24:12.850 回答