1. 添加依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.2</version>
<exclusions>
<exclusion>
<artifactId>commons-codec</artifactId>
<groupId>commons-codec</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
2. 工具类
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author polaris <450733605@qq.com>
* Description JWT Token工具类
* Date 2020-12-28 17:53
* Version 1.0.0
*/
public class JwtUtil {
// 设置过期时间
private static final long EXPIRE_DATE = 1 * 60 * 1000;
// token秘钥(长度需要达到加密算法要求,过短会抛异常)
private static final String TOKEN_SECRET = "1AsdadSAS123daXXsdafsadpolarisdf34234fdfsdfdsfdsafsd";
// 密钥(服务重启后会随机生成,不推荐使用)
private static final Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
/**
* 生成token
*
* @param param 自定义参数或者覆盖jwt参数,默认有效期30分钟
* @return
*/
public static String token(Map<String, Object> param) {
return token(param, null);
}
/**
* 生成token(指定有效期)
*
* @param param
* @param expireTimeMillis 有效期(毫秒数)
* @return
*/
public static String token(Map<String, Object> param, Long expireTimeMillis) {
String token;
Date expire = new Date(System.currentTimeMillis() + EXPIRE_DATE);
if (expireTimeMillis != null && expireTimeMillis > 0) {
expire = new Date(System.currentTimeMillis() + expireTimeMillis);
}
try {
// 设置头部信息
Map<String, Object> header = new HashMap<>();
header.put("typ", "JWT");
header.put("alg", "HS256");
JWTCreator.Builder builder = JWT.create()
.withHeader(header);
if (param != null && param.size() > 0) {
param.forEach((k, v) -> {
builder.withClaim(k, String.valueOf(v));
});
}
token = builder
.withExpiresAt(expire)
.sign(algorithm);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return token;
}
/**
* 验证Token有效性
* @param token
* @return
*/
public static boolean verify(String token) {
try {
JWTVerifier verifier = JWT.require(algorithm).build();
verifier.verify(token);
return true;
}catch (TokenExpiredException te){
System.err.println(te.getMessage());
return false;
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 解析Token
*
* @param token
* @return
*/
public static Map<String, Object> parserToken(String token) {
Map<String, Object> map = new HashMap<>();
try {
DecodedJWT t=JWT.require(algorithm).build().verify(token);
Map<String, Claim> claims=t.getClaims();
if(claims!=null && claims.size()>0){
claims.forEach((k,v) -> {
if("exp".equalsIgnoreCase(k)){
map.put(k, v.asDate());
}else{
map.put(k, v.asString());
}
});
}
}catch (TokenExpiredException te){
System.err.println(te.getMessage());
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
return map;
}
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);
}
}