一聚教程网:一个值得你收藏的教程网站

热门教程

ssm项目实现用户登陆持久化token代码示例

时间:2022-06-29 02:30:36 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下ssm项目实现用户登陆持久化token代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

用户登录持久化就是每次访问不用账号密码来校验身份,在用户登录第一次之后会返回一个token字符串,之后的访问客户端将这个token加到请求体里发给服务器就可以验证身份了。

利用Jedis和JWT创建用户token

1、JWT创建token

maven依赖:

        
            com.auth0
            java-jwt
            3.3.0
        

创建JWT工具类

用于创建token和解析token

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 map = new HashMap();
        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 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服务

        
            redis.clients
            jedis
            2.9.0
        

然后设计一个Jedis工具类将其封装

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;
    }
}

热门栏目