1. 程式人生 > 實用技巧 >spring boot下通過攔截器完成訪問許可權限制

spring boot下通過攔截器完成訪問許可權限制

遇到一個需求是:要為使用者設定不同的選單、資料訪問許可權。對於一些特定型別的資料,有的使用者可以看有的使用者則不可以。一開始沒有太多思路,後來一想是不是可以把"特定型別"這個引數通過@PathVariable註解加到路徑上,這樣就可以通過攔截器攔截後,校驗此使用者是否可以訪問這個路徑(型別)下的資料了。
話不多說,以下為具體實踐

  1. 攔截器配置類

    @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
                }
            };
        }
    
    
    }
    
    
  2. 註冊攔截器

    //註冊攔截器
        @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));
                }
    
            };
        }
    
  3. 配置要攔截的路徑

    @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/**