JWT是什么我就不做介绍了,在这只说一下JWT的开源的第三方JJWT的初步使用
话不多说,上代码
JwtUtil.class
public class JwtUtil
{
private String jianshu;
/**
* 由字符串生成加密key
* @return
*/
public SecretKey generalKey(){
String stringKey = jianshu+Constant.JWT_SECRET;
byte[] encodedKey = Base64.decodeBase64(stringKey);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
/**
* 创建jwt
* @param id
* @param subject
* @param ttlMillis
* @return
* @throws Exception
*/
public String createJWT(String id, String subject, long ttlMillis) throws Exception {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
SecretKey key = generalKey();
JwtBuilder builder = Jwts.builder()
.setId(id)
.setIssuedAt(now)
.setSubject(subject)
.signWith(signatureAlgorithm, key);
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
return builder.compact();
}
/**
* 解密jwt
* @param jwt
* @return
* @throws Exception
*/
public Claims parseJWT(String jwt) throws Exception{
SecretKey key = generalKey();
Claims claims = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(jwt).getBody();
return claims;
}
/**
* 生成subject信息
* @param user
* @return
*/
public static String generalSubject(t_user user){
JSONObject jo = new JSONObject();
jo.put("userId", user.getId());
jo.put("mobile", user.getMobile());
return jo.toJSONString();
}
}
Constant.class
public class Constant
{
/**
* jwt
*
*/
public static final String JWT_ID = "jwt";
public static final String JWT_SECRET = "hong1mu2zhi3ruan4jian5";
public static final int JWT_TTL = 60*60*1000; //millisecond
public static final int JWT_REFRESH_INTERVAL = 55*60*1000; //millisecond
public static final int JWT_REFRESH_TTL = 12*60*60*1000; //millisecond
}
在这只是JJWT的最基本的实现,后续会继续完善.
点这里:JJWT的github地址
JJWT的jar包:jar包地址