该篇文章以《Redis实现短信验证码登录》这篇文章为基础,以Redis和Java拦截器为核心,对登录功能展开研究和应用。
获取验证码
/**
* @author issavior
*/
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RefreshTokenInterceptor(redisTemplate))
.addPathPatterns("/**").order(0);
registry.addInterceptor(new MyHandlerInterceptor()).addPathPatterns("/user/pay").order(1);
}
}
刷新token、添加和移除用户信息到Threadlocal、
/**
* @author issavior
*/
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {
private final RedisTemplate<String, Object> redisTemplate;
public RefreshTokenInterceptor(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String token = request.getHeader("authToken");
if (StrUtil.isBlank(token)) {
return true;
}
String key = "token:"+token;
Issa issa = (Issa)redisTemplate.opsForValue().get(key);
if (issa == null) {
return true;
}
UserHolder.saveUser(issa);
redisTemplate.expire(key, 60, TimeUnit.SECONDS);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
UserHolder.removeUser();
}
}
/**
* @author issavior
*/
public class MyHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 1.判断是否需要拦截(ThreadLocal中是否有用户)
if (UserHolder.getUser() == null) {
// 没有,需要拦截,设置状态码
response.setStatus(401);
// 拦截
return false;
}
// 有用户,则放行
return true;
}
}
/**
* @author issavior
*/
public class UserHolder {
private static final ThreadLocal<Issa> tl = new ThreadLocal<>();
public static void saveUser(Issa user){
tl.set(user);
}
public static Issa getUser(){
return tl.get();
}
public static void removeUser(){
tl.remove();
}
}
《核心技术系列专栏汇总》
需要 大厂面试题
、简历模版
、电子书
、学习资料
等关注【公众号】回复「 1024 」即可。