HttpSecurity常用方法详解

antMatcher与antMatchers的区别以及使用场景

@EnableWebSecurity
public class MultiHttpSecurityConfig {
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) { 1
      auth
          .inMemoryAuthentication()
              .withUser("user").password("password").roles("USER").and()
              .withUser("admin").password("password").roles("USER", "ADMIN");
  }

  @Configuration
  @Order(1)                                                        2
  public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
      protected void configure(HttpSecurity http) throws Exception {
//这种情况下有两个HttpSecurity,未定义@Order就默认最后,多个未定义或者相同Order就按照定义顺序。需要/api/开头的url匹配Role为 Admin的User。
//.antMatcher("/api/**") 过滤掉非/api/开头的请求,如果不用antMatcher,所有请求都会进入,进入的请求只有两条路,允许通过(permitall)
//或者导向login(authenticated),但我们并不想处理
          http
              .antMatcher("/api/**")                               3
              .authorizeRequests()
                  .anyRequest().hasRole("ADMIN")
                  .and()
              .httpBasic();
      }
  }    
/*https://stackoverflow.com/questions/30819337/multiple-antmatchers-in-spring-security
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/admin/login").permitAll()
范围小的放在前面,范围大的放在后面,想法的话范围小的就不会匹配,按照范围大的处理。
比如上面,/admin/login按照hasRole("ADMIN")处理。*/
  @Configuration                                                   4
  public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
              .authorizeRequests()
                  .anyRequest().authenticated()
                  .and()
              .formLogin();
      }
  }
}

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();
}
//springsecurity源码  如下 : pattern = "/**";  this.matcher = null;  说明 /** 就不需要进行请求匹配。
public AntPathRequestMatcher(String pattern, String httpMethod, boolean caseSensitive, UrlPathHelper urlPathHelper) {
        Assert.hasText(pattern, "Pattern cannot be null or empty");
        this.caseSensitive = caseSensitive;
        if (!pattern.equals("/**") && !pattern.equals("**")) {
            if (pattern.endsWith("/**") && pattern.indexOf(63) == -1 && pattern.indexOf(123) == -1 && pattern.indexOf(125) == -1 && pattern.indexOf("*") == pattern.length() - 2) {
                this.matcher = new AntPathRequestMatcher.SubpathMatcher(pattern.substring(0, pattern.length() - 3), caseSensitive);
            } else {
                this.matcher = new AntPathRequestMatcher.SpringAntMatcher(pattern, caseSensitive);
            }
        } else {
            pattern = "/**";
            this.matcher = null;
        }

        this.pattern = pattern;
        this.httpMethod = StringUtils.hasText(httpMethod) ? HttpMethod.valueOf(httpMethod) : null;
        this.urlPathHelper = urlPathHelper;
    }

authorizeRequests()

授权管理控制的方法(),这个方法返回一个ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry对象。Security所有的权限控制都基于这个类进行控制。
如:http.authorizeRequests().anyRequest().authenticated();要求所有接口都需要进行权限认证,这个类中的anyRequest()即所有接口, 等同于 http.authorizeRequests().antMatchers("/").authenticated() ;

//所有接口都不需要权限认证
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方法配置多个角色的访问权限,如

// 在这个代码中要求以/test开头的路由需要进行角色认证(这里要求user角色),而其他接口只要登录即可访问
http.authorizeRequests().antMatchers("/test/**").hasAnyRole("user","admin").antMatchers("/**").authenticated();

匹配规则

URL匹配

requestMatchers() 配置一个request Mather数组,参数为RequestMatcher 对象,其match 规则自定义,需要的时候放在最前面,对需要匹配的的规则进行自定义与过滤
authorizeRequests() URL权限配置
antMatchers() 配置一个request Mather 的 string数组,参数为 ant 路径格式, 直接匹配url
anyRequest 匹配任意url,无参 ,最好放在最后面

保护URL

authenticated() 保护UrL,需要用户登录
permitAll() 指定URL无需保护,一般应用与静态资源文件
hasRole(String role) 限制单个角色访问,角色将被增加 “ROLE_” .所以”ADMIN” 将和 “ROLE_ADMIN”进行比较. 另一个方法是hasAuthority(String authority)
hasAnyRole(String… roles) 允许多个角色访问. 另一个方法是hasAnyAuthority(String… authorities)
access(String attribute) 该方法使用 SPEL, 所以可以创建复杂的限制 例如如access(“permitAll”), access(“hasRole(‘ADMIN’) and hasIpAddress(‘123.123.123.123’)”)
hasIpAddress(String ipaddressExpression) 限制IP地址或子网

登录login

formLogin() 基于表单登录
loginPage() 登录页
defaultSuccessUrl 登录成功后的默认处理页
failuerHandler登录失败之后的处理器
successHandler登录成功之后的处理器
failuerUrl登录失败之后系统转向的url,默认是this.loginPage + “?error”

登出logout

logoutUrl 登出url , 默认是/logout, 它可以是一个ant path url
logoutSuccessUrl 登出成功后跳转的 url 默认是"/login?logout"
logoutSuccessHandler 登出成功处理器,设置后会把logoutSuccessUrl 置为null

多个antMatchers在Spring

在这里插入图片描述

  • 5
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值