zoukankan      html  css  js  c++  java
  • requestMatchers()和authorizeRequests()区别

    原文:https://blog.csdn.net/tianlong1569/article/details/108398149

    HttpSecurity全名为org.springframework.security.config.annotation.web.builders.HttpSecurity

    这个类是Spring Security中继承WebSecurityConfigurerAdapter时需要复写的接口中的一个重要参数,用于配置Security重要的拦截及权限控制。这方法在父类中保护方法。

    同时这个类也是OAuth2.0中资源服务继承ResourceServerConfigurerAdapter时,需要复写的接口中的一个重要参数。也是用于配置Security的重要拦截及权限。因此当我们使用Security及OAuth2.0时会有配置重复的问题。这点需要注意。这个方法在父类中属于公开方法。

    HttpSecurity 重要方法:

    requestMatchers()
    取得RequestMatcherConfigurer对象并配置允许过滤的路由;如requestMatchers().anyRequest()等同于http.authorizeRequests().anyRequest().access("permitAll");如下面两个例子:

    @Override
    public void configure(HttpSecurity http) throws Exception {	
            //只允许路由由test开头的需要进行权限认证,其他的接口不需要权限认证;requestMatchers().anyRequest()即所有接口可以不进行认证;	
    	http.requestMatchers().anyRequest().and().authorizeRequests().antMatchers("/test/*").authenticated();
    }
    
    @Override
    public void configure(HttpSecurity http) throws Exception {
    	//只有以/test 开头的路由需要进行权限认证;其他路由不需要权限认证
    	http.requestMatchers().antMatchers("/test/**").and().authorizeRequests().antMatchers("/**").authenticated();
    }
    

    上面两个例子中可以看出:http.requestMatchers().anyRequest().and().authorizeRequests().antMatchers("/test/").authenticated();配置和http.requestMatchers().antMatchers("/test/").and().authorizeRequests().antMatchers("/**").authenticated();配置后的效果是完全一样的。

    authorizeRequests()

    授权管理控制的方法,这个方法返回一个ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry对象。Security所有的权限控制都基于这个类进行控制。如:http.authorizeRequests().anyRequest().authenticated();要求所有接口都需要进行权限认证,这个类中的anyRequest()即所有接口,等同于http.authorizeRequests().antMatchers("/").authenticated(); 而其中的authenticated()则要求必须进行权限认证。而http.authorizeRequests().antMatchers("/").permitAll();这个配置中permitAll方法则要求所有接口都不需要进行权限认证。另外这两个代码中antMatchers方法则是配置匹配规则。即哪些接口需要进行权限认证或不需要进行权限认证。

    //所有接口都不需要权限认证
    http.authorizeRequests().antMatchers("/**").permitAll();
    //所有接口都要进行权限认证
    http.authorizeRequests().antMatchers("/**").authenticated();
    //只有以test开头的接口需要进行权限认证
    http.authorizeRequests().antMatchers("/test/**").authenticated();
    

    http.authorizeRequests().antMatchers("/test/").hasRole("user").antMatchers("/").authenticated();在这个代码中要求以/test开头的路由需要进行角色认证(这里要求user角色),而其他接口只要登录即可访问。当我们需要配置多个角色时可以通过hasAnyRole方法配置多个角色的访问权限,如

    http.authorizeRequests().antMatchers("/test/**").hasAnyRole("user","admin").antMatchers("/**").authenticated();

  • 相关阅读:
    CSS learnning...
    软件工程课程建议
    结对编程(三)
    结对编程(二)
    关于结对编程的感想
    关于“Durian”调查问卷的心得体会
    我的软件工程课目标
    软件工程课程建议
    进阶版《结对编程》
    结对编程实现四则运算
  • 原文地址:https://www.cnblogs.com/daikainan/p/14333094.html
Copyright © 2011-2022 走看看