问题
上一篇博客中提到使用redis来存用户的登录信息,解决了session不共享问题。
在拦截器中,重新设置了用户信息的有效期,保证只要用户一直请求就永不过期。但是并不是每个请求都会经过拦截器的(因为登录拦截器,不是每个请求都需要验证登录),那么就会导致用户比如一直在访问不会经过拦截器的请求,突然就会提示用户未登录,这就不合适了。
解决
新添加一个拦截器,专门用于拦截所有请求,只用于获取token,获取用户信息,将用户信息放入redis,刷新token的有效期,放行。
小提示
redis客户端工具可以查看key的有效期。
实现思路图
刷新token的拦截器
package com.xkj.org.interceptor;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.xkj.org.dto.UserDTO;
import com.xkj.org.utils.RedisConstants;
import com.xkj.org.utils.SystemConstants;
import com.xkj.org.utils.UserHolder;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Struct;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class RefreshTokenInterceptor implements HandlerInterceptor {
private StringRedisTemplate stringRedisTemplate;
public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//从请求头中获取用户登录的token
String token = request.getHeader("authorization");
if(StrUtil.isBlank(token)) {
//直接放行,不做处理
return true;
}
Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
//entries不会为null,只需要判断是否为空map即可
if(entries.isEmpty()) {
//直接放行,不做处理
return true;
}
//将map转成UserDTO
UserDTO userDTO = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
//将UserDTO存入ThreadMap中
UserHolder.saveUser(userDTO);
//刷新token的有效期
stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, RedisConstants.LOGIN_USER_TTL,
TimeUnit.MINUTES);
//放行
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
UserHolder.removeUser();
}
}
登录拦截器
package com.xkj.org.interceptor;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.xkj.org.dto.UserDTO;
import com.xkj.org.utils.RedisConstants;
import com.xkj.org.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
UserDTO user = UserHolder.getUser();
if(ObjectUtil.isNull(user)) {
//未登录,拦截
response.setStatus(401);
return false;
}
//放行
return true;
}
}
拦截器配置类
package com.xkj.org.config;
import com.xkj.org.interceptor.LoginInterceptor;
import com.xkj.org.interceptor.RefreshTokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer{
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//添加token刷新拦截器,用户拦截所有请求,获取header中token,获取redis中的用户信息,存入ThreadLocal中,刷新token的有效期
//设置order,优先执行,值越大优先级越低
registry.addInterceptor(new RefreshTokenInterceptor(stringRedisTemplate)).addPathPatterns("/**").order(0);
//添加登录验证拦截器,排除一些不需要拦截的url
registry.addInterceptor(new LoginInterceptor())
.excludePathPatterns(
"/user/code",
"/user/login",
"/blog/hot",
"/shop/**",
"/shop-type/**",
"/upload/**",
"voucher/**"
).order(1);
}
}
ThreadLocal使用
package com.xkj.org.utils;
import com.xkj.org.dto.UserDTO;
public class UserHolder {
private static final ThreadLocal<UserDTO> t1 = new ThreadLocal<>();
public static void saveUser(UserDTO userDTO) {
t1.set(userDTO);
}
public static UserDTO getUser() {
return t1.get();
}
public static void removeUser() {
t1.remove();
}
}