该篇文章以《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();
}
}
到此这篇关于Redis + Java拦截器实现用户匿名和非匿名访问的文章就介绍到这了,更多相关Redis Java用户匿名和非匿名访问内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:Redis + Java拦截器实现用户匿名和非匿名访问
基础教程推荐
猜你喜欢
- ConditionalOnProperty配置swagger不生效问题及解决 2023-01-02
- JDK数组阻塞队列源码深入分析总结 2023-04-18
- java基础知识之FileInputStream流的使用 2023-08-11
- Java并发编程进阶之线程控制篇 2023-03-07
- Java数据结构之对象比较详解 2023-03-07
- springboot自定义starter方法及注解实例 2023-03-31
- java实现多人聊天系统 2023-05-19
- Java实现线程插队的示例代码 2022-09-03
- Java实现查找文件和替换文件内容 2023-04-06
- Java文件管理操作的知识点整理 2023-05-19