10分钟了解JSON Web令牌(JWT):
https://baijiahao.baidu.com/s?id=1608021814182894637&wfr=spider&for=pc
POM文件引用:
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
代码中的应用,写一个工具类就行:JwtUtils.java
package com.example.util;
import Constant.SystemConstant;
import com.sun.jersey.core.util.Base64;
import com.sun.xml.internal.ws.spi.db.DatabindingException;
import io.jsonwebtoken.*;
import sun.text.normalizer.NormalizerBase;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
public class JwtUtils {
/**
* 签发JWT
* @param id
* @param subject 可以是JSON数据 尽可能少
* @param ttlMillis
* @return String
*/
public static String createJWT(String id,String subject,long ttlMillis){
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
SecretKey secretKey = generalKey();
JwtBuilder builder = Jwts.builder().setId(id).setSubject(subject)
.setIssuer("user")
.setIssuedAt(now)
.signWith(signatureAlgorithm,secretKey);
if (ttlMillis >= 0){
long expMillis = nowMillis + ttlMillis;
Date expDate = new Date(expMillis);
builder.setExpiration(expDate);
}
return builder.compact();
}
/**
* 检查结果
* @param jwtStr
* @return
*/
public static CheckResult validateJWT(String jwtStr){
CheckResult checkResult = new CheckResult();
Claims claims = null;
try{
claims = parseJWT(jwtStr);
checkResult.setSuccess(true);
checkResult.setClaims(claims);
}catch (ExpiredJwtException e){
checkResult.setErrCode(SystemConstant.JWT_ERRCODE_EXPIRE.getCode());
checkResult.setSuccess(false);
}catch (SignatureException e){
checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL.getCode());
checkResult.setSuccess(false);
}catch (Exception e){
checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL.getCode());
checkResult.setSuccess(false);
}
return checkResult;
}
/**
* 生成key
* @return
*/
public static SecretKey generalKey(){
byte[] encodedKey = Base64.decode(SystemConstant.JWT_SECERT.name());
SecretKey secretKey = new SecretKeySpec(encodedKey,0,encodedKey.length,"AES");
return secretKey;
}
/**
* 解析jwt
* @param jwt
* @return
*/
public static Claims parseJWT(String jwt){
SecretKey secretKey = generalKey();
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
}
}