Spring boot使用拦截器实现访问权限限制

发布时间:2020-10-27 21:21:00 作者:Leah
来源:亿速云 阅读:318

这篇文章运用简单易懂的例子给大家介绍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<String> path = interceptorProperties.getPath();
        //要排除的路径
        List<String> 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<String> path = new ArrayList<>();
  /**
   * 需要忽略的接口通配
   */
  private List<String> excludePath = new ArrayList<>();
  public List<String> getPath() {
    return path;
  }
  public void setPath(List<String> path) {
    this.path = path;
  }
  public List<String> getExcludePath() {
    return excludePath;
  }
  public void setExcludePath(List<String> excludePath) {
    this.excludePath = excludePath;
  }
}
dbnet:
 interceptor:
  path: /dbnet/**,/datanet/**
  excludePath: /dbnet/detail,/datanet/recommend,/datanet/count,/datanet/getKeys,/datenet/metadata/**

关于Spring boot使用拦截器实现访问权限限制就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. spring boot加入拦截器Interceptor过程解析
  2. Spring Boot如何使用过滤器和拦截器分别实现REST接口简易安全认证

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring boot spring boo

上一篇:使用python如何实现粒子群算法

下一篇:使用Python return语句如何实现结果返回调用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》