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);}
3. 在登录拦截器中进行令牌验证
@Autowiredprivate StringRedisTemplate stringRedisTemplate;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//令牌验证String token = request.getHeader("Authorization");//验证tokentry {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响应状态码为401response.setStatus(401);//不放行return false;}}
4.当密码更新成功时,需重新登录,删除旧令牌
//调用service完成密码更新userService.updatePwd(newPwd);//删除redis中对应的tokenValueOperations<String, String> operations = stringRedisTemplate.opsForValue();operations.getOperations().delete(token);