如何使用Apache Commons Codec解码Java中的JWT(Header和Body)?

时间:2016-08-12 11:29:07

标签: apache jwt apache-commons-codec

我正在使用#include "A.h" QTimer A::updateTimer.setInverval(100); // I need to set it's inverval to 100ms // but only once in the beginning of it's life time A::A(){... } ~A::A(){... } 解码以下JWT。我们怎么做到这一点?

Apache Commons Codec

这应该检索 eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0Iiwicm9sZXMiOiJST0xFX0FETUlOIiwiaXNzIjoibXlzZ WxmIiwiZXhwIjoxNDcxMDg2MzgxfQ.1EI2haSz9aMsHjFUXNVz2Z4mtC0nMdZo6bo3-x-aRpw HeaderBody部分。什么代码?

2 个答案:

答案 0 :(得分:30)

你走了:

import org.apache.commons.codec.binary.Base64;
@Test
    public void testDecodeJWT(){
        String jwtToken = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0Iiwicm9sZXMiOiJST0xFX0FETUlOIiwiaXNzIjoibXlzZWxmIiwiZXhwIjoxNDcxMDg2MzgxfQ.1EI2haSz9aMsHjFUXNVz2Z4mtC0nMdZo6bo3-x-aRpw";
        System.out.println("------------ Decode JWT ------------");
        String[] split_string = jwtToken.split("\\.");
        String base64EncodedHeader = split_string[0];
        String base64EncodedBody = split_string[1];
        String base64EncodedSignature = split_string[2];

        System.out.println("~~~~~~~~~ JWT Header ~~~~~~~");
        Base64 base64Url = new Base64(true);
        String header = new String(base64Url.decode(base64EncodedHeader));
        System.out.println("JWT Header : " + header);


        System.out.println("~~~~~~~~~ JWT Body ~~~~~~~");
        String body = new String(base64Url.decode(base64EncodedBody));
        System.out.println("JWT Body : "+body);        
    }

以下输出:

------------ Decode JWT ------------
~~~~~~~~~ JWT Header ~~~~~~~
JWT Header : {"alg":"HS256"}
~~~~~~~~~ JWT Body ~~~~~~~
JWT Body : {"sub":"test","roles":"ROLE_ADMIN","iss":"myself","exp":1471086381}

答案 1 :(得分:0)

这是一种非软件包导入方式:

            java.util.Base64.Decoder decoder = java.util.Base64.getUrlDecoder();
            String[] parts = jwtToken.split("\\."); // split out the "parts" (header, payload and signature)

            String headerJson = new String(decoder.decode(parts[0]));
            String payloadJson = new String(decoder.decode(parts[1]));
            //String signatureJson = new String(decoder.decode(parts[2]));

REGLESLESS(这是org.apache.commons.codec.binary.Base64的替代方法)...您可能还想将这些json片段推到pojo的位置。

然后您可以将这些json片段转换为pojo。

标头是“动态的”,因此您可能想转换为键值对(在Java中又称为“映射”)

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

public class JwtTokenHeaders {

    private final Map<String, Object> jsonMap; // = new HashMap<String, Object>();

    public JwtTokenHeaders(String jsonString) {

        ObjectMapper mapper = new ObjectMapper();
        //String jsonString = "{\"name\":\"JavaInterviewPoint\", \"department\":\"blogging\"}";

        //Map<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            // convert JSON string to Map
            this.jsonMap = mapper.readValue(jsonString,
                    new TypeReference<Map<String, String>>() {
                    });
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public String toString() {
        return org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(this);
    }
}

有效载荷更加静态,因此您可以映射到pojo .....您可以获取json并在此处创建匹配的pojo:

http://pojo.sodhanalibrary.com/

您要执行此操作..(使用在线工具创建MyPojo)

类似这样的东西:

//import com.fasterxml.jackson.databind.DeserializationFeature;
//import com.fasterxml.jackson.databind.ObjectMapper;
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            MyPojo tp = mapper.readValue(payloadJson, MyPojo.class);

如果http://pojo.sodhanalibrary.com/将来不复存在,只需在互联网上搜索“将在线json转换为pojo”就可以了。