JWT实际上就是一个字符串,它由三部分组成,头部、载荷与签名组成。
其实际的载荷(载荷(Payload))
将对象编码得到:Header 头信息
# 头里面放加密算法 及签名信息
{
"type": "JWT",
"alg": "BASE64"
}
编码字符串:
eyJ0eXBlIjoiSldUIiwiYWxnIjoiQkFTRTY0In0=
Map<String,String> header = new HashMap<String, String>();
header.put("type","JWT");
header.put("alg","BASE64");
String jsonString = JSON.toJSONString(header);
System.out.println(jsonString);
BASE64Encoder base64Encoder = new BASE64Encoder();
String encode = base64Encoder.encode(jsonString.getBytes("UTF-8"));
System.out.println(encode);
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] bytes = base64Decoder.decodeBuffer(encode);
System.out.println(new String(bytes,"UTF-8" ));
{
"iss": "springboot", #该JWT 的签发者,可填/不填
"iat": d, # 签发时间 可填/不填
"exp": 5s, # token 过期时间。uninx 时间戳 可填/不填
"aud": "www.baidu.com", # 接受 jwt方 可填/不填
"sub": "www.baidu.com" # 面向的用户 可填/不填
}
加密解密:
Map<String,String> payLoadMap = new HashMap<>();
payLoadMap.put("iss","springboot");
payLoadMap.put("iat","1234567");
payLoadMap.put("exp","100s");
payLoadMap.put("aud","ww.baidu.com");
payLoadMap.put("sub","ww.baidu.com");
String toString = JSON.toJSONString(payLoadMap);
System.out.println(toString);
HmacCore.HmacSHA256 hmacSHA256 = new HmacCore.HmacSHA256();
String encode1 = base64Encoder.encode(toString.getBytes("UTF-8"));
System.out.println(encode1);
System.out.println(new String(base64Decoder.decodeBuffer(encode1),"UTF-8"));
利用JDK 自带的BASE64Encoder 和 BASE64Decoder,方便的完成基于 BASE64 的编码和解码
eyJhdWQiOiJ3dy5iYWlkdS5jb20iLCJzdWIiOiJ3dy5iYWlkdS5jb20iLCJpc3MiOiJzcHJpbmdi
b290IiwiZXhwIjoiMTAwcyIsImlhdCI6IjEyMzQ1NjcifQ==
对获取的头信息用(.)拼接,再用HS256 加密
eyJ0eXBlIjoiSldUIiwiYWxnIjoiQkFTRTY0In0=.eyJhdWQiOiJ3dy5iYWlkdS5jb20iLCJzdWIiOiJ3dy5iYWlkdS5jb20iLCJpc3MiOiJzcHJpbmdib290IiwiZXhwIjoiMTAwcyIsImlhdCI6IjEyMzQ1NjcifQ==
在这里插入代码片