使用 Hutools工具类 生成随机验证码
String code = RandomUtil.randomNumbers(6);
将验证码保存到Redis
redisTemplate.opsForValue().set(
REDIS_CODE_PRE + phone, code, 2, TimeUnit.MINUTES
);
使用拦截器实现登录拦截和Token刷新
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Autowired
private StringRedisTemplate template;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new TokenInterceptor(template)).addPathPatterns(
"/**"
).order(0);
registry.addInterceptor(new LoginInterceptor()).addPathPatterns(
"/user"
).order(2);
}
}
拦截所有请求
用于刷新Token有效期,并将用户信息保存到ThreadLocal。之后使用ThreadLocal获取用户信息。
在请求头上获取Token
String token = request.getHeader("authorization"));
使用ThreadLocal保存用户信息
public class UserHolder {
private static final ThreadLocal<UserDTO> tl = new ThreadLocal<UserDTO>();
public static void saveUser(UserDTO user) {
tl.set(user);
}
public static UserDTO getUser() {
return tl.get();
}
public static void removeUser() {
tl.remove();
}
}
拦截需要登录才能访问的接口(/user 个人信息)
用于判断是否登录,通过ThreadLocal判空操作获取登录信息。
@Data
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (UserHolder.getUser() == null) {
response.setStatus(401);
return false;
}
return true;
}
}