用户登录持久化就是每次访问不用账号密码来校验身份,在用户登录第一次之后会返回一个token字符串,之后的访问客户端将这个token加到请求体里发给服务器就可以验证身份了。
利用jedis和jwt创建用户token
1、jwt创建token
maven依赖:
1 2 3 4 5 |
<dependency> <groupid>com.auth0</groupid> <artifactid>java-jwt</artifactid> <version>3.3.0</version> </dependency> |
创建jwt工具类
用于创建token和解析token
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
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
首先讲讲jedis,jedis是集成了redis的一些命令操作,将其封装的java客户端,一般在其上封装一层作为业务使用,封装如下:
首先导入maven包,这里也需要启动redis服务
1 2 3 4 5 |
<dependency> <groupid>redis.clients</groupid> <artifactid>jedis</artifactid> <version>2.9.0</version> </dependency> |
然后设计一个jedis工具类将其封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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; } } |
到此这篇关于ssm项目实现用户登陆持久化(token)的文章就介绍到这了,更多相关ssm 用户登陆持久化内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
原文链接:https://blog.csdn.net/sinat_41905822/article/details/89043642
查看更多关于ssm项目实现用户登陆持久化(token)的详细内容...