该篇文章以《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拦截器实现用户匿名和非匿名访问
猜你喜欢
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- 深入了解Spring的事务传播机制 2023-06-02
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- JSP页面间传值问题实例简析 2023-08-03
- JSP 制作验证码的实例详解 2023-07-30
- Java中的日期时间处理及格式化处理 2023-04-18
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- Java实现顺序表的操作详解 2023-05-19