Redis + Java拦截器实现用户匿名和非匿名访问

2022-11-13 10:11:58 用户 访问 匿名

该篇文章以《Redis实现短信验证码登录》这篇文章为基础,以Redis和Java拦截器为核心,对登录功能展开研究和应用。

需求

  • 对所有的接口按需分类
  • 一些接口可以匿名访问
  • 一些接口必须登录才可以访问
  • 刷新token

实现截图

获取验证码

用验证码完成登录,并获取token

用token实现访问非匿名访问接口

核心代码

WebMvcConfigurer


@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void addInterceptors(InterceptorReGIStry registry) {
        registry.addInterceptor(new RefreshTokenInterceptor(redisTemplate))
                .addPathPatterns("
@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();
    }
}

判断用户是否有权限


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


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用户匿名和非匿名访问内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章