栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring boot如何基于拦截器实现访问权限限制

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring boot如何基于拦截器实现访问权限限制

遇到一个需求是:要为用户设置不同的菜单、数据访问权限。对于一些特定类型的数据,有的用户可以看有的用户则不可以。一开始没有太多思路,后来一想是不是可以把"特定类型"这个参数通过@PathVariable注解加到路径上,这样就可以通过拦截器拦截后,校验此用户是否可以访问这个路径(类型)下的数据了。

话不多说,以下为具体实践

拦截器配置类

@Configuration
public class UserInterceptorConfig {
  //为了保证IDbnetUserService提前实例化,能在userInterceptor使用
  //ConditionalOnMissingBean可以保证只有一个IDbnetUserService的实例
  @Bean
  @ConditionalOnMissingBean(IDbnetUserService.class)
  public IDbnetUserService dbnetUserService() {
    return new DbnetUserServiceImpl();
  }
  //拦截器
  @Bean(name = "userInterceptor")
  public HandlerInterceptor userInterceptor(IDbnetUserService dbnetUserService) {
    return new HandlerInterceptor() {
      @Override
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 //url = request.getRequestURI() 判断url是否可以有权限访问而返回true或者false
      }
    };
  }
}

注册拦截器

//注册拦截器
  @Bean
  public WebMvcConfigurer registerInterceptor(@Qualifier("userInterceptor") HandlerInterceptor userInterceptor) {
    return new WebMvcConfigurerAdapter() {
      @Override
      public void addInterceptors(InterceptorRegistry registry) {
 //要拦截的路径
 List path = interceptorProperties.getPath();
 //要排除的路径
 List excludePath = interceptorProperties.getExcludePath();
 registry.addInterceptor(userInterceptor).addPathPatterns(path.stream().toArray(String[]::new))
     .excludePathPatterns(excludePath.stream().toArray(String[]::new));
      }

    };
  }

配置要拦截的路径

@Component
@ConfigurationProperties(prefix = "dbnet.interceptor")
public class InterceptorProperties {
  
  private List path = new ArrayList<>();
  
  private List excludePath = new ArrayList<>();
  public List getPath() {
    return path;
  }
  public void setPath(List path) {
    this.path = path;
  }
  public List getExcludePath() {
    return excludePath;
  }
  public void setExcludePath(List excludePath) {
    this.excludePath = excludePath;
  }
}
dbnet:
 interceptor:
  path: /dbnet/**,/datanet/**
  excludePath: /dbnet/detail,/datanet/recommend,/datanet/count,/datanet/getKeys,/datenet/metadata/**

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/131091.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号