需要添加依赖这里使用的JJWT
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
public class SpringbootSecurityoauth2ApplicationTests{
// 当前时间
long date = System.currentTimeMillis();
// 失效时间(60秒)
long exp = date + 68 * 1000;
/**
* <p>
* @Date: 2021/6/10
* <p>
* @Description: 生成jwt
*/
@Test
public void testJwt(){
JwtBuilder jwt = Jwts.builder()
// 唯一ID{"id","888"}
.setId("888")
// 接受的用户{"sub":"Rose"}
.setSubject("Rose")
// 签发时间{"iat","...."}
.setIssuedAt(new Date())
// 签名算法,级秘钥
.signWith(SignatureAlgorithm.HS256,"xxxx")
// 设置失效时间
.setExpiration(new Date(exp));
String token = jwt.compact();
System.out.println(token);
// .需要转义
String [] split = token.split("\\.");
System.out.println("- -------------------");
System.out.println(Base64Codec.BASE64.decodeToString(split[0]));
System.out.println(Base64Codec.BASE64.decodeToString(split[1]));
// 这个会乱码
System.out.println(Base64Codec.BASE64.decodeToString(split[2]));
}
// 解析token
@Test
public void testPaseToken(){
String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODgiLCJzdWIiOiJSb3NlIiwiaWF0IjoxNjIzMzA5NDYwLCJleHAiOjE2MjMzMDk1Mjd9.xlSFy-8Wk66rKwGsQJuOhEK9fdDrAI40TF3jswBQAVY";
// 解析token,获取claims,jwt中何在申明
Claims claims = (Claims)Jwts.parser()
// 秘钥,主要这个和签发的秘钥要一样
.setSigningKey("xxxx")
.parse(token)
.getBody();
System.out.println("id="+claims.getId());
System.out.println("sub="+claims.getSubject());
System.out.println("iat="+claims.getIssuedAt());
}
/**
* <p>
* @Date: 2021/6/10
* <p>
* @Description: 生成jwt(自定义申明)
*/
@Test
public void testJwtHasEnhacer(){
JwtBuilder jwt = Jwts.builder()
// 唯一ID{"id","888"}
.setId("888")
// 接受的用户{"sub":"Rose"}
.setSubject("Rose")
// 签发时间{"iat","...."}
.setIssuedAt(new Date())
// 签名算法,级秘钥
.signWith(SignatureAlgorithm.HS256,"xxxx")
// 自定义声明
.claim("name","jack")
.claim("log","xx.jpg");
String token = jwt.compact();
System.out.println(token);
// .需要转义
String [] split = token.split("\\.");
System.out.println("- -------------------");
System.out.println(Base64Codec.BASE64.decodeToString(split[0]));
System.out.println(Base64Codec.BASE64.decodeToString(split[1]));
// 这个会乱码
System.out.println(Base64Codec.BASE64.decodeToString(split[2]));
}
// 解析自定义声明的claim
@Test
public void testPaseHasEnhacer(){
String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODgiLCJzdWIiOiJSb3NlIiwiaWF0IjoxNjIzMzEwMDQ0LCJuYW1lIjoiamFjayIsImxvZyI6Inh4LmpwZyJ9.a4BlmvCM-YcRovOYf2rS_foPQW6okVZX76YRsjpGWYQ";
// 解析token,获取claims,jwt中何在申明
Claims claims = (Claims)Jwts.parser()
// 秘钥,主要这个和签发的秘钥要一样
.setSigningKey("xxxx")
.parse(token)
.getBody();
System.out.println("id="+claims.getId());
System.out.println("sub="+claims.getSubject());
System.out.println("iat="+claims.getIssuedAt());
// 解析自定义是声明的 claim
System.out.println("name="+claims.get("name"));
System.out.println("log="+claims.get("log"));
}
}