首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Jose4J将JWT的主体提取为JSON

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

Stack Overflow用户
提问于 2021-03-03 13:41:15
回答 1查看 310关注 0票数 0

我希望使用Jose4j将JWT的主体提取为JSON。这个是可能的吗?

我们需要支持一个定制的验证,它可以是任意的,简单的,也可以是非常复杂的,取决于客户。我们需要JSON形式的主体,这样我们就可以将它作为特定于客户的Javascript方法的参数传递。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-04 13:24:12

在从getRawJson()获得的JwtClaims对象上调用JSON将为您提供JWT的JSON有效负载,这听起来像是您要寻找的东西。

https://bitbucket.org/b_c/jose4j/wiki/JWT%20Examples中的以下代码片段进行了轻微修改,以显示正在使用的getRawJson()

代码语言:javascript
复制
    // 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);
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66458269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档