【问题标题】:How to Get JSON String for header/payload from JWT token using java-jwt如何使用 java-jwt 从 JWT 令牌获取标头/有效负载的 JSON 字符串
【发布时间】:2020-09-05 12:27:24
【问题描述】:

java-jwt 中是否有一种方法可以将令牌作为单个 JSON 字符串(或至少将标头和有效负载作为两个 JSON 字符串)返回? JJWT 支持吗?

查看https://github.com/auth0/java-jwt 的教程,我没有看到这种方法(消息的各个部分有单独的 getter,但我没有看到任何将完整消息作为 JSON 字符串返回的内容)。

getHeader() 和 getHeader() 方法返回编码字符串。我正在尝试以 JSON 格式获取标头和有效负载(类似于https://jwt.io/ 中显示的内容)。我该怎么做?

到目前为止的代码如下:

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

public class CreateTokenExampleIntegrationTest {

    private static final Logger logger = LoggerFactory.getLogger(CreateTokenExampleIntegrationTest.class);

    @Test
    public void shouldCreateToken() {
        logger.info("Starting test...");
        // create the token
        String key = "foobarkey";
        Algorithm alg = Algorithm.HMAC256(key);
        String issuer = "me";
        JWTCreator.Builder jwt = JWT.create();
        jwt.withIssuer(issuer);
        jwt.withClaim("createdBy", "CreateTokenExampleIntegrationTest");
        jwt.withClaim("purpose", "test");
        jwt.withClaim("msg", "Hello World.");
        String token = jwt.sign(alg);
        logger.info("Created token: \n" + token);
        // read the token
        JWTVerifier verifier = JWT.require(alg)
                .withIssuer(issuer)
                .build();
        DecodedJWT decoded = verifier.verify(token);
        logger.info("Header: \n" + decoded.getHeader());
        logger.info("Payload: \n" + decoded.getPayload());
        logger.info("Done.");
    }

}

这是输出:

2020-05-19 08:23:31,387 08:23:31.387 [main] INFO  (CreateTokenExampleIntegrationTest.java:19) - Starting test...
2020-05-19 08:23:32,226 08:23:32.226 [main] INFO  (CreateTokenExampleIntegrationTest.java:30) - Created token: 
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtc2ciOiJIZWxsbyBXb3JsZC4iLCJjcmVhdGVkQnkiOiJDcmVhdGVUb2tlbkV4YW1wbGVJbnRlZ3JhdGlvblRlc3QiLCJwdXJwb3NlIjoidGVzdCIsImlzcyI6Im1lIn0.VmYsToj1PKBzJKQuXEyiKuJA-GkNVit0Ylh44dVF2UI
2020-05-19 08:23:32,273 08:23:32.273 [main] INFO  (CreateTokenExampleIntegrationTest.java:36) - Header: 
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
2020-05-19 08:23:32,273 08:23:32.273 [main] INFO  (CreateTokenExampleIntegrationTest.java:37) - Payload: 
eyJtc2ciOiJIZWxsbyBXb3JsZC4iLCJjcmVhdGVkQnkiOiJDcmVhdGVUb2tlbkV4YW1wbGVJbnRlZ3JhdGlvblRlc3QiLCJwdXJwb3NlIjoidGVzdCIsImlzcyI6Im1lIn0
2020-05-19 08:23:32,273 08:23:32.273 [main] INFO  (CreateTokenExampleIntegrationTest.java:38) - Done.

编辑:这是基于公认答案的完整解决方案:

代码:

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

public class CreateTokenExampleIntegrationTest {

    private static final Logger logger = LoggerFactory.getLogger(CreateTokenExampleIntegrationTest.class);

    @Test
    public void shouldCreateToken() {
        logger.info("Starting test...");
        // create the token
        String key = "foobarkey";
        Algorithm alg = Algorithm.HMAC256(key);
        String issuer = "me";
        JWTCreator.Builder jwt = JWT.create();
        jwt.withIssuer(issuer);
        jwt.withClaim("createdBy", "CreateTokenExampleIntegrationTest");
        jwt.withClaim("purpose", "test");
        jwt.withClaim("msg", "Hello World.");
        String token = jwt.sign(alg);
        logger.info("Created token: \n" + token);
        // read the token
        JWTVerifier verifier = JWT.require(alg)
                .withIssuer(issuer)
                .build();
        DecodedJWT decoded = verifier.verify(token);
        // header
        String encHeader = decoded.getHeader();
        String header = decode(encHeader);
        logger.info("Header: \n" + encHeader + "\n" + header);
        // payload
        String encPayload = decoded.getPayload();
        String payload = decode(encPayload);
        logger.info("Payload: \n" + encPayload + "\n" + payload);
        // done
        logger.info("Done.");
    }

    public String decode(final String base64) {
        return StringUtils.newStringUtf8(Base64.decodeBase64(base64));
    }

}

输出:

2020-05-19 10:13:29,146 10:13:29.146 [main] INFO  (CreateTokenExampleIntegrationTest.java:21) - Starting test...
2020-05-19 10:13:30,031 10:13:30.031 [main] INFO  (CreateTokenExampleIntegrationTest.java:32) - Created token: 
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtc2ciOiJIZWxsbyBXb3JsZC4iLCJjcmVhdGVkQnkiOiJDcmVhdGVUb2tlbkV4YW1wbGVJbnRlZ3JhdGlvblRlc3QiLCJwdXJwb3NlIjoidGVzdCIsImlzcyI6Im1lIn0.VmYsToj1PKBzJKQuXEyiKuJA-GkNVit0Ylh44dVF2UI
2020-05-19 10:13:30,102 10:13:30.102 [main] INFO  (CreateTokenExampleIntegrationTest.java:41) - Header: 
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
{"typ":"JWT","alg":"HS256"}
2020-05-19 10:13:30,103 10:13:30.103 [main] INFO  (CreateTokenExampleIntegrationTest.java:45) - Payload: 
eyJtc2ciOiJIZWxsbyBXb3JsZC4iLCJjcmVhdGVkQnkiOiJDcmVhdGVUb2tlbkV4YW1wbGVJbnRlZ3JhdGlvblRlc3QiLCJwdXJwb3NlIjoidGVzdCIsImlzcyI6Im1lIn0
{"msg":"Hello World.","createdBy":"CreateTokenExampleIntegrationTest","purpose":"test","iss":"me"}
2020-05-19 10:13:30,103 10:13:30.103 [main] INFO  (CreateTokenExampleIntegrationTest.java:47) - Done.

【问题讨论】:

    标签: java jwt


    【解决方案1】:

    我查看了java-jwt,我认为它不会输出payloadheader JSON 字符串而不是base64-encoded。此外,“正常”JSON 字符串只是 JWTDecoder(参见 here)的 cunstructor 和 JWTCreator(参见 here)的私有不可访问字段中的临时本地字符串,它们永远不会“暴露给公众”。

    因此,您要么必须自己解码base64 字符串,要么通过反射访问JWTCreator 的私有字段。但在这种情况下,我肯定会选择手动解码字符串。这可能看起来像这样(等于JWTDecoderdoes it):

    public String decodeToJson(final String base64){
            return StringUtils.newStringUtf8(Base64.decodeBase64(base64));
    }
    
    DecodedJWT decoded = verifier.verify(token); // in your Test-Class
    
    final String headerJson = decodeToJson(decoded.getHeader());
    final String payloadJson = decodeToJson(decoded.getPayload());
    

    【讨论】:

    • 完美运行,谢谢!我将此添加为原始问题中的编辑。
    猜你喜欢
    • 2021-12-24
    • 2019-10-29
    • 2022-01-04
    • 2018-11-18
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    • 2018-09-15
    相关资源
    最近更新 更多