spring security antMatchers相关内容

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

来源:https://stackoverflow.com/questions/35890540/when-to-use-spring-securitys-antmatcher

antMatcher用在多个HttpSecurity的场景下,用来为每个HttpSecurity过滤

@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 {
          http
              .antMatcher("/api/**")                               3
              .authorizeRequests()
                  .anyRequest().hasRole("ADMIN")
                  .and()
              .httpBasic();
      }
  }    

  @Configuration                                                   4
  public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

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

这种情况下有两个HttpSecurity,未定义@Order就默认最后,多个未定义或者相同Order就按照定义顺序。

需要/api/开头的url匹配Role为Admin的User。

.antMatcher("/api/**") 过滤掉非/api/开头的请求,如果不用antMatcher,所有请求都会进入,进入的请求只有两条路,允许通过(permitall)或者导向login(authenticated),当我们并不想处理

二.antMathchers匹配规则

https://www.cnblogs.com/cyjch/archive/2012/03/28/2421353.html

ANT通配符有三种:
? 匹配任何单字符
* 匹配0或者任意数量的字符
** 匹配0或者更多的目录

三.antMatchers的顺序

https://stackoverflow.com/questions/30819337/multiple-antmatchers-in-spring-security

.antMatchers("/admin/**").hasRole("ADMIN")

.antMatchers("/admin/login").permitAll()

范围小的放在前面,范围大的放在后面,想法的话范围小的就不会匹配,按照范围大的处理。

比如上面,/admin/login按照hasRole("ADMIN")处理。

 

.antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/admin/login").permitAll()

转载于:https://www.cnblogs.com/ptqueen/p/8450028.html

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值