ps: 自己研究的工具类,目前都还不算完善,有些只是个笔记的作用,如果有问题,希望可以联系,我麻溜去修改,谢谢。
<!--jwt-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtUtil {
private static String key = "3866a78125581a861c4baef4b4142d8f";
private static long ttl = 3600 * 1000;//默认存活时间
public static String createToken(UserBase user, long ttl) {
Map<String, Object> claims = createClaims(user);
return createJWT(claims);
}
public static String createToken(UserBase user) {
return createToken(user, ttl);
}
public static UserVo parseToken(String jwtStr) {
Claims claims = null;
try {
claims = parseJWT(jwtStr);
return parseClaims(claims);
} catch (Exception e) {
return null;
}
}
private static Map<String, Object> createClaims(UserBase user) {//改成自己需要转换的类
Map<String, Object> claims = new HashMap<>();
claims.put("userName", user.getName());
claims.put("image", user.getImage());
claims.put("id", user.getId());
return claims;
}
private static UserBase parseClaims(Claims claims) {
UserBase userBase = new UserBase();
userBase.setName(claims.get("userName", String.class));
userBase.setImage(claims.get("image", String.class));
userBase.setId(claims.get("id", Long.class));
return userBase;
}
/**
* 创建JWT字符串
*
* @param claims 载荷内容
* @param ttl 有效日期,秒 默认1小时
*/
private static String createJWT(Map<String, Object> claims, long ttl) {
JwtUtil.ttl = ttl * 1000;
return createJWT(claims);
}
/**
* @param claims 载荷
* @return token
*/
private static String createJWT(Map<String, Object> claims) {
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
JwtBuilder builder = Jwts.builder()
.setIssuedAt(now)
.signWith(SignatureAlgorithm.HS256, key);
if (claims != null) {
builder.setClaims(claims);
}
if (ttl > 0) {
builder.setExpiration(new Date(nowMillis + ttl));
}
return builder.compact();
}
/**
* 创建Token
*
* @param key 关键字
* @param ttl 秒值
* @return
*/
private static String createJWT(String key, long ttl) {
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
JwtBuilder builder = Jwts.builder()
.setId(key)
.setIssuedAt(now)
.signWith(SignatureAlgorithm.HS256, JwtUtil.key);
if (ttl > 0) {
ttl = ttl * 1000;
builder.setExpiration(new Date(nowMillis + ttl));
}
return builder.compact();
}
/**
* 解析字符串,过期则报错
*
* @param jwtStr
* @return
*/
private static Claims parseJWT(String jwtStr) {
return Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(jwtStr)
.getBody();
}
public static void setTtl(long ttl) {
JwtUtil.ttl = ttl;
}
}