spring security antMatchers相关内容

您所在的位置:网站首页 matchers spring security antMatchers相关内容

spring security antMatchers相关内容

2023-08-11 04:29| 来源: 网络整理| 查看: 265

一.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()


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3