Spring Boot 生成与解析Jwt
Maven依赖
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version>
</dependency>
生成&解析
package yang;import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;import java.util.Date;
import java.util.HashMap;
import java.util.Map;@Slf4j
public class TestMain {@Testpublic void run() {Map<String, Object> claims = new HashMap<>();claims.put("id", 1);claims.put("username", "宇阳");// 创建JwtString jwt = Jwts.builder().setClaims(claims) // 载荷:自定义的数据.signWith(SignatureAlgorithm.HS256, "yuyang") // 签名算法.setExpiration(new Date(System.currentTimeMillis() + 24 * 3600 * 1000)) // 有效期:以当前的时间戳往后加一天.compact(); // 转换为字符串log.info("生成Jwt:{}", jwt);// 解析JwtClaims data = Jwts.parser().setSigningKey("yuyang") // 自定义解密的秘钥.parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiZXhwIjoxNzA4OTMwMjMwLCJ1c2VybmFtZSI6IuWuh-mYsyJ9.6Iqhflkx900okTibiyLuYjwCDSgLBgYJ0RWB4-jt2ME") // 指定需要解析的Token令牌.getBody();log.info("解析Jwt:{}", data);}
}
工具类
package yang.utils;import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;import java.util.Date;
import java.util.Map;public class JwtUtils {private static String signKey = "yuyang"; //签名密钥private static Long expire = 43200000L; //有效时间:12小时 单位毫秒// 生成Jwtpublic static String createJwt(Map<String, Object> claims){String jwt = Jwts.builder().addClaims(claims).signWith(SignatureAlgorithm.HS256, signKey).setExpiration(new Date(System.currentTimeMillis() + expire)).compact();return jwt;}// 解析Jwtpublic static Claims parseJWT(String jwt){Claims claims = Jwts.parser().setSigningKey(signKey).parseClaimsJws(jwt).getBody();return claims;}
}
使用工具类
public class TestMain {@Testpublic void run() {Map<String, Object> claims = new HashMap<>();claims.put("id", 1);claims.put("username", "宇阳");// 创建JwtString jwt = JwtUtils.createJwt(claims);log.info("生成Jwt:{}", jwt);// 解析JwtClaims data = JwtUtils.parseJWT(jwt);log.info("解析Jwt:{}", data);}
}