4.JWT组成
1.组成
1.标头(Header)
2.载荷(PayLoad)
3.签名(Signature)
2.Header
- 标头通常由两部分组成:令牌类型(JWT)以及所用签名算法,他会用Base64编码JWT第一部分
3.PageLoad
-令牌的第二部分,声明是有关实体和其他数据的声明。
同样,他会使用Base64编码组成JWT的第二部分
4.JWT实战
package com.example.demo;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.utils.JWTUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.swing.*;
import java.util.Calendar;
import java.util.HashMap;
@SpringBootTest
class SpringbootjwtApplicationTests {
@Test
void contextLoads() { //获取Token
HashMap<String, Object> map = new HashMap<>();
Calendar instance = Calendar.getInstance();
instance.add(Calendar.SECOND,20*60*60);
String sign = JWT.create()
.withHeader(map) //header
.withClaim("username", "小王") //payload
.withClaim("userid", 21)
.withExpiresAt(instance.getTime())//指定过期时间
.sign(Algorithm.HMAC256("!QWER"));//签名
System.out.println(sign);
}
@Test
public void test(){ //解析Token
//开始解码
JWTVerifier verifier = JWT.require(Algorithm.HMAC256("!QWER")).build();
DecodedJWT verify = verifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MzAwMTMzMDcsInVzZXJpZCI6MjEsInVzZXJuYW1lIjoi5bCP546LIn0.hpZ-KFZiabl4U_1HovouYY2tGSkNcSDoWwP6N6IRHWI");
System.out.println(verify.getClaim("username").asString());
System.out.println(verify.getClaim("userid").asInt());
System.out.println(verify.getExpiresAt());
}
}
5.JWT工具包
package com.example.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class JWTUtils {
/**
* 生成token
*/
//签名可能需要单独拿出来
private static final String SIGN = "!QWER";
public static String getToken(Map<String,String>map){
Calendar instance = Calendar.getInstance();
instance.add(Calendar.DATE,7); //默认七天过期
JWTCreator.Builder builder = JWT.create();
map.forEach((k,v)->{
builder.withClaim(k,v);
});
String sign = builder
.withExpiresAt(instance.getTime())//指定过期时间
.sign(Algorithm.HMAC256(SIGN));//签名
return sign;
}
/**
* 验证已经有的token
*/
public static DecodedJWT verify(String sign){
return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(sign);
}
// /**
// * 获取Token信息的方法
// */
// public static DecodedJWT getTokenInfo(String sign){
// DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(sign);
// return verify;
// }
}