在pom.xml中加入依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.2</version>
</dependency>
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @Description 令牌处理器
* @Author WangKun
* @Date 2021/6/24 16:09
* @Version
*/
public class TokenUtil {
/**
* token加解密秘钥
**/
private static final String SECRET_KEY = "WK_0612";
/**
* @Description 生成令牌
* @param userName
* @param password
* @param userId
* @Throws
* @Return java.lang.String
* @Date 2021-07-09 16:19:59
* @Author WangKun
**/
public static String createToken(String userName, String password ,String userId) throws UnsupportedEncodingException {
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
//生效时间
calendar2.add(Calendar.SECOND, 0);
Date effectTime = calendar2.getTime();
//过期时间60min后
calendar1.add(Calendar.MINUTE, 60);
Date maturityTime = calendar1.getTime();
Map<String, Object> header = new HashMap<>(2);
header.put("alg", "HS256");
header.put("typ", "JWT");
return JWT.create()
.withHeader(header)
.withClaim("password", password)
.withClaim("userName", userName)
.withClaim("userId", userId)
.withIssuedAt(new Date())
.withExpiresAt(maturityTime)
.withNotBefore(effectTime)
.withJWTId(userId)
.sign(Algorithm.HMAC256(SECRET_KEY));
}
/**
* @Description 解析验证令牌
* @param token
* @Throws
* @Return java.util.Map<java.lang.String,com.auth0.jwt.interfaces.Claim>
* @Date 2021-07-09 16:20:17
* @Author WangKun
**/
public static Map<String, Claim> verifyToken(String token) throws UnsupportedEncodingException {
//秘钥解密
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
DecodedJWT jwt = null;
try {
jwt = verifier.verify(token);
} catch (JWTVerificationException e) {
e.printStackTrace();
if (e.getMessage().startsWith("The Token can't be used before")) {
throw new InvalidClaimException("登录凭证未生效");
}
if (e.getMessage().startsWith("The Token has expired on")) {
throw new InvalidClaimException("登录凭证已过期,请重新登录");
}
}
if (jwt != null) {
return jwt.getClaims();
}
return null;
}
}
使用:
String token = TokenUtil.createToken(userName,password ,userId);
解析:
Map<String, Claim> claimMap = TokenUtil.verifyToken(token);
String userName = claimMap.get("userName").asString();
String password = claimMap.get("password").asString();
String userId = claimMap.get("userId").asString()
异常信息捕捉
try {
Map<String, Claim> claimMap = TokenUtil.verifyToken(token);
// 业务处理(token正常情况下处理)
} catch (Exception e) {
// token不正常情况下处理,返回异常信息
JSONObject objet = new JSONObject();
objet.put("status", false);
objet.put("msg", e.getMessage());
Writer out = resp.getWriter();
out.write(objet.toString());
}