主要的代码:
主要可以实现生成token,然后这个可以保存在reddish里面这样每一次用户操作鉴权就可以正常的进行了
public class JwtToken {
/**
* jwt密钥
*/
private static String jwtSecret = "6077df7fc3a34e26a61c034d5ec8245d";
/**
* token有效期为3天半,白天登录时夜晚过期
*/
private static long expTime = 35 * 100 * 24 * 60 * 60L;
public static String buildToken(String appKey){
if(null==appKey){
return null;
}
SecretKey key = new SecretKeySpec(jwtSecret.getBytes(),0, jwtSecret.getBytes().length, "AES");
// 设置算法为HS256
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
Date now = new Date(System.currentTimeMillis());
Date exp = new Date(System.currentTimeMillis() + expTime);
JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT").setHeaderParam("alg", "HS256").setIssuedAt(now)
.claim("appKey", appKey).setExpiration(exp).signWith(signatureAlgorithm, key);
return builder.compact();
}
public static boolean isEffectiveToken(String token) {
boolean isEffectiveToken = true;
try {
Claims claims = Jwts.parser().setSigningKey(jwtSecret.getBytes()).parseClaimsJws(token).getBody();
/*isEffectiveToken = claims.getExpiration().getTime() - System.currentTimeMillis() > 0;*/
}catch (ExpiredJwtException e){
e.printStackTrace();
isEffectiveToken = false;
}
return isEffectiveToken;
}
public static String getUserAccount(String token){
if(null == token){
return null;
}
Claims claims = Jwts.parser().setSigningKey(jwtSecret.getBytes()).parseClaimsJws(token).getBody();
return claims.get("appKey").toString();
}
}
依赖的jar
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>