1.pom.xml中引入redis依赖
<!-- Redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.将登录成功的token存储到redis中
if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
//登录成功
Map<String,Object> claims = new HashMap<>();
claims.put("username",loginUser.getUsername());
claims.put("id",loginUser.getId());
String token = JwtUtil.genToken(claims);
//把token存储到redis中
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
operations.set(token,token,12, TimeUnit.HOURS);
return Result.success(token);
}
-
在登录拦截器中进行令牌验证
@Autowired private StringRedisTemplate stringRedisTemplate; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //令牌验证 String token = request.getHeader("Authorization"); //验证token try { ValueOperations<String, String> operations = stringRedisTemplate.opsForValue(); String redisToken = operations.get(token); if(redisToken == null){ //token已经失效了 throw new RuntimeException(); } Map<String, Object> claims = JwtUtil.parseToken(token); //把业务数据存储到ThreadLocal中 ThreadLocalUtil.set(claims); //放行 return true; } catch (Exception e) { //http响应状态码为401 response.setStatus(401); //不放行 return false; } }
4.当密码更新成功时,需重新登录,删除旧令牌
//调用service完成密码更新
userService.updatePwd(newPwd);
//删除redis中对应的token
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
operations.getOperations().delete(token);