该篇文章以《Redis实现短信验证码登录》这篇文章为基础,以Redis和Java拦截器为核心,对登录功能展开研究和应用。
需求
- 对所有的接口按需分类
- 一些接口可以匿名访问
- 一些接口必须登录才可以访问
- 刷新token
实现截图
获取验证码
用验证码完成登录,并获取token
用token实现访问非匿名访问接口
核心代码
WebMvcConfigurer
/**
* @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);
}
}
HandlerInterceptor
刷新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;
}
}
ThreadLocal
/**
* @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 」即可。