用户登录持久化就是每次访问不用账号密码来校验身份,在用户登录第一次之后会返回一个token字符串,之后的访问客户端将这个token加到请求体里发给服务器就可以验证身份了。7 p7 @4 V* _ u, H6 k) M
利用Jedis和JWT创建用户token
1 m- p/ \8 a) V$ P 1、JWT创建token
2 |7 M, F& \! H" U, u. w9 x maven依赖:) `6 e0 J8 Q1 v' {* b. Z9 m$ P
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>
创建JWT工具类,用于创建token和解析token/ Z M8 a% j; T6 ?) ~- x) _) v8 |
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
& v) Y) y' V: W5 o, S/ \* m 首先讲讲Jedis,Jedis是集成了redis的一些命令操作,将其封装的java客户端,一般在其上封装一层作为业务使用,封装如下:
* {5 L# C4 \8 C4 D 首先导入maven包,这里也需要启动redis服务
- P+ R) x1 r: ?2 s( | <dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
然后设计一个Jedis工具类将其封装
6 U+ F* X9 d- R9 R% D 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;
}
}