微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Jose4J 将 JWT 的主体提取为 JSON

如何解决使用 Jose4J 将 JWT 的主体提取为 JSON

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

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

解决方法

在从 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);
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。