一. 引入JAR包
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.45</version>
</dependency>
二. 創(chuàng)建JWT工具類(lèi)
public class JWTUtils {
/** token秘鑰,請(qǐng)勿泄露 */
public static final String SECRET = "#@$_&^#@DSWER#@";
/**
*
* @param userName : 用戶(hù)名
* @return 生成的字符串Token值
*/
public static String createToken(String userName) {
Date iatDate = new Date();
// expire time
Calendar nowTime = Calendar.getInstance();
// nowTime.add(Calendar.SECOND, 1 * 24 * 60 * 60);
nowTime.add(Calendar.SECOND, 1* 24 * 60 * 60); //一天過(guò)期
//過(guò)期時(shí)間1天
Date expiresDate = nowTime.getTime();
// header Map
Map<String, Object> map = new HashMap<>();
map.put("alg", "HS256");
map.put("typ", "JWT");
// build token
// param backups {iss:Service, aud:APP}
String token = JWT.create().withHeader(map) // header
.withClaim("iss", "Service") // payload
.withClaim("aud", "APP")
.withClaim("userName", null == userName ? null : userName)
.withIssuedAt(iatDate) // sign time
.withExpiresAt(expiresDate) // expire time
.sign(Algorithm.HMAC256(SECRET)); // signature
return token;
}
/**
* 解密Token
*
* @param token: 服務(wù)器端生成的Token發(fā)送給客戶(hù)端,客戶(hù)端再傳遞過(guò)來(lái)需要驗(yàn)證的Token
* @return 返回驗(yàn)證結(jié)果: code:{0:success, 1:fail}
*/
public static Map<String,Object> verifyToken(String token) {
Map<String, Claim> claims = null;
Map<String,Object> map = new HashMap<>();
map.put("code",1); //默認(rèn)為驗(yàn)證失敗 0: 驗(yàn)證成功
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
claims = verifier.verify(token).getClaims();
map.put("code",0);
map.put("msg", "success");
}
catch (SignatureVerificationException e){
map.put("msg","簽名無(wú)效");
}
catch (AlgorithmMismatchException e){
map.put("msg","簽名算法不匹配");
}
catch (TokenExpiredException e){
map.put("msg","token過(guò)期");
}
map.put("claims",claims);
return map;
}
}
二. 生成及驗(yàn)證測(cè)試
public static void main(String[] args) {
//生成Token, 登陸成功后,將生成的Token返回給客戶(hù)端
String token = JWTUtils.createToken("xiaomi");
//收到客戶(hù)端通過(guò)ajax傳遞過(guò)來(lái)的token,將驗(yàn)證結(jié)果返回給用戶(hù)
//客戶(hù)將根據(jù)這里返回的code,msg進(jìn)行判斷驗(yàn)證
String json = JSON.toJSONString(JWTUtils.verifyToken(token));
//使用阿里的fastjson2類(lèi)
System.out.println(json);
}