相关POM引用
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version> </dependency>
相关代码
package com.dhh;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**@author denghanghui
* @Date 2020 03 06
* Json Web Token 简单示例
*/
public class TWJTemple {
public static void main(String[] args) {
SignatureAlgorithm signatureAlgorithm = getSignatureAlgorithm();
SecretKey key = getKey();
//设置启动时间和过期时间
long nowMillis = System.currentTimeMillis();
long expMillis = nowMillis + 300000;
Date now = new Date(nowMillis);
Date expDate = new Date(expMillis);
//JWT中存的信息
Map map=new HashMap();
map.put("username","yunnengkeji");
map.put("password","123456789");
JwtBuilder builder = Jwts.builder();
builder.setId("1").setSubject("jwt").setIssuer("denghanghui").setIssuedAt(now).signWith(signatureAlgorithm,key).setExpiration(expDate).addClaims(map);
//获取koken
String token= builder.compact();
Claims claims=null;
//解析token内的容器
try {
claims = parseJWT(token);
Object username= claims.get("username");
Object password= claims.get("password");
System.out.println("*****************************************************************");
System.out.println(username);
System.out.println(password);
System.out.println("*****************************************************************");
}catch (Exception e){
System.out.println("解析异常");
}
}
/**
* 解析JWT字符串获取Claims容器
* @param jwt JWT字符串
* @return Claims容器
* @throws Exception 解析异常
*/
public static Claims parseJWT(String jwt) throws Exception {
SecretKey secretKey = getParseKey();
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(jwt)
.getBody();
}
/**
* 获取解析用密钥
* @return 解析用密钥对象
*/
public static SecretKey getParseKey(){
byte[] encodedKey = Base64.decodeBase64("denghanghui");
return new SecretKeySpec(encodedKey, 0, encodedKey.length, "");
}
/**
* 获取加密用密钥
* @return 加密用密钥对象
*/
public static SecretKey getKey(){
byte[] encodedKey = Base64.decodeBase64("denghanghui");
return new SecretKeySpec(encodedKey, 0, encodedKey.length, "");
}
/**
* 设置加密签名算法
* @return 设置加密签名算法
*/
public static SignatureAlgorithm getSignatureAlgorithm(){
return SignatureAlgorithm.HS256;
}
}