gitee地址:https://gitee.com/langhai666/langhai-blog
github地址:https://github.com/Allenkuzma/langhaiblogs
本篇文章的完整代码请阅读上面 浪海博客 的源码。
cc.langhai.controller.user.LoginController#loginEnter (用户登录功能实现)
cc.langhai.interceptor.LoginInterceptor(自定义拦截器)
实现思路
第一步:在实现登录功能的时候,生成一份和用户秘钥,在redis和cookie当中都进行存储。
第二步:在访问需要登录的功能时候,从cookie当中获取用户秘钥和redis中的秘钥进行对比。从而实现七天内免密码登录。
具体实现
第一段代码在登录的时候,分别在redis和cookie存储用户想关联的秘钥信息。
// 使用hutool工具进行md5秘钥生成,后面在拼接上UUID。
String md5 = DigestUtil.md5Hex(username + systemConfig.getSecret());
UUID uuid = UUID.randomUUID();
String cipher = uuid + md5;
// 将秘钥信息存储在cookie当中。
Cookie cookie = new Cookie("userLoginCipher" + username, cipher);
cookie.setPath("/");
cookie.setMaxAge(7 * 24 * 60 * 60);
response.addCookie(cookie);
// 将秘钥信息存储到redis当中。
redisTemplate.opsForValue().set("userLoginCipher" + username, cipher, 7 * 24 * 60, TimeUnit.MINUTES);
第二段代码在拦截器中拦截,获取cookie当中的秘钥信息,再从redis当中获取秘钥信息进行对比。如果核实成功,从而进行登录。
// 遍历cookie从而拿到当中的秘钥信息。
Cookie[] cookies = request.getCookies();
// ... ...
// 从redis中获取秘钥信息。
String redis = redisTemplate.opsForValue().get(cookie.getName());
// ... ...
// 如果核实成功,则进行登录。
session.setAttribute("user", user);
session.setMaxInactiveInterval(60 * 60);
上面已经提供大部分代码,具体实现细节可以参考 浪海博客 源码,或者根据逻辑自行实现。