用户登录持久化就是每次访问不用账号密码来校验身份,在用户登录第一次之后会返回一个token字符串,之后的访问客户端将这个token加到请求体里发给服务器就可以验证身份了。: y+ O6 @' }3 }' {( A7 y$ `
利用Jedis和JWT创建用户token
+ F6 [4 o, _$ {, e& z! A/ S 1、JWT创建token / [* e! A) }& [- X9 ~* |! T
maven依赖:
2 L2 H) U: y3 b" W0 G <dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency> 创建JWT工具类,用于创建token和解析token! r- W- R' w1 n. J. H9 n) v* L
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
public class JWTUtils {
/**
* 公钥
*/
private static String SECRET = "qiang"; //此处随便设置一个自己的加密符号
public static String createToken(int id, String username,
String type) throws Exception {
// 签发时间
Date iatDate = new Date();
// 过期时间,7天时间
Calendar nowTime = Calendar.getInstance();
nowTime.add(Calendar.HOUR, 24 * 7);
Date experiesDate = nowTime.getTime();
Map<String, Object> map = new HashMap<String, Object>();
map.put("alg", "HS256");
map.put("typ", "JWT");
String token = JWT.create()
.withHeader(map)
.withClaim("id", id)
.withClaim("username", username)
.withClaim("type", type)
.withExpiresAt(experiesDate) // 设置过期的日期
.withIssuedAt(iatDate) // 签发时间
.sign(Algorithm.HMAC256(SECRET)); // 加密
return token;
}
/**
* 解密
*/
public static Map<String, Claim> verifyToken(String token) throws Exception {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
DecodedJWT jwt = null;
try {
jwt = verifier.verify(token); //核实token
} catch (Exception e) {
throw new Exception("登录过期");
}
return jwt.getClaims(); //返回的是解析完的token,是一个map,里面有id,username,type键值对
}
}2、JedisUtil缓存token
6 L+ K k' u7 d% Z/ g 首先讲讲Jedis,Jedis是集成了redis的一些命令操作,将其封装的java客户端,一般在其上封装一层作为业务使用,封装如下:! r' G# w8 \3 z4 |
首先导入maven包,这里也需要启动redis服务7 s1 Z! Q- a2 o R d- y( R
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency> 然后设计一个Jedis工具类将其封装
' D, ?/ | _ B2 p" |3 v, s import redis.clients.jedis.Jedis;
public class JedisUtils {
private static Jedis jedis;
//初始化
private static void init() {
jedis = new Jedis("localhost");
}
//在redis中设置键值对存储
public static void setToken(String id, String token, int day) {
int second = day * 60 * 60 * 24;
JedisUtils.init();
jedis.set(String.valueOf(id), token); //根据id存储token
jedis.expire(String.valueOf(id), second); //设置token持续时间
}
public static String getToken(String id) {
JedisUtils.init();
String token = jedis.get(String.valueOf(id)); //获取token
return token;
}
}