1. 添加依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.3</version>
</dependency>
2. 工具类
import io.jsonwebtoken.*;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author polaris <450733605@qq.com>
* Description 数据质量管理Token工具类
* Date 2020-12-28 13:16
* Version 1.0.0
*/
public class JwtUtil {
// 默认过期时间
private static final long EXPIRE_TIME = 1 * 60 * 1000;
// 密钥(服务重启后会随机生成,不推荐使用)
private static final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
//private static final Key key = Keys.secretKeyFor(signatureAlgorithm);
// token秘钥(长度需要达到加密算法要求,过短会抛异常)
// 以下错误是由于更改了${TOKEN_SECRET}
// JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.
private static final String TOKEN_SECRET = "1AsdadSAS123daXXsdafsadpolarisdf34234fdfsdfdsfdsafsd";
/**
* 生成token
*
* @param param 自定义参数或者覆盖jwt参数,默认有效期30分钟
* @return
*/
public static String token(Map<String, Object> param) {
String token = Jwts.builder()
.setClaims(param)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
.signWith(generalKey(), signatureAlgorithm)
.compact();
return token;
}
/**
* 生成token(指定有效期)
*
* @param param
* @param expireTimeMillis 有效期(毫秒数)
* @return
*/
public static String token(Map<String, Object> param, Long expireTimeMillis) {
SecretKey secretKey = generalKey();
long nowMillis = System.currentTimeMillis();
JwtBuilder builder = Jwts.builder()
.setClaims(param)
.signWith(secretKey, signatureAlgorithm);
if (expireTimeMillis >= 0) {
long expMillis = nowMillis + expireTimeMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
return builder.compact();
}
/**
* 解析Token
*
* @param token
* @return
*/
public static Map<String, Object> parserToken(String token) {
Map<String, Object> map = new HashMap<>();
Jws<Claims> claimsJws;
try {
claimsJws = Jwts.parserBuilder().setSigningKey(generalKey()).build().parseClaimsJws(token);
claimsJws.getBody().forEach((k, v) -> map.put(k, v));
} catch (ExpiredJwtException ee) {
System.err.println(ee.getMessage());
return null;
} catch (Exception e) {
System.err.println(">>>>>>>>>>>>>>>>>" + e.getMessage());
return null;
}
return map;
}
/**
* 验证Token有效性
* @param token
* @return
*/
public static boolean verify(String token) {
try {
Jwts.parserBuilder().setSigningKey(generalKey()).build().parseClaimsJws(token);
return true;
}catch (ExpiredJwtException ee){
System.err.println(ee.getMessage());
return false;
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 由字符串生成加密key
*
* @return
*/
public static SecretKey generalKey() {
byte[] encodedKey = TOKEN_SECRET.getBytes();// Base64.decodeBase64(TOKEN_SECRET);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "HmacSHA256");
return key;
}
public static void main(String[] args) {
Map<String, Object> param = new HashMap<>();
param.put("username", "sha san");
param.put("password", "123");
String token = token(param);
System.out.println(String.format("token:{%s}",token));
System.out.println("-----------------------------------------------------");
token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZCI6IjEyMyIsImV4cCI6MTYwOTE1MjU2OCwidXNlcm5hbWUiOiJzaGEgc2FuIn0._eOF0ftDWuL0G2kBBXWn2sft5UwNhqxAaYHJmfvT0KA";
if(verify(token)){
System.out.println("验证成功!");
}else{
System.out.println("验证失败!");
}
Map<String, Object> resMap =parserToken(token);
System.out.println("=====================================================");
System.out.println(resMap);
}
}