requestMatchers()方法与authorizeRequests()区别,ResourceServerConfigurerAdapter与WebSecurityConfigurerAdapt

一、requestMatchers()方法与authorizeRequests()区别

1.理解这两个方法的区别首先要知道springsecurity中,每声明一个adapter实例,就会产生一条过滤器链,一个请求过来要走哪个过滤器链就是由requestMatchers()方法配置的url决定的。请求匹配上requestMatchers()配置的过滤器链后,在进一步的详细控制则是authorizeRequests()决定的。

一句话概括就是requestMatchers()配置的是哪些url进行安全控制,authorizeRequests()配置的是如何进行控制

例如:

下面这个adapter只对/api1/order/**和/api1/address/**两个url生效。(即当请求匹配这两个url其中之一时,才会进行安全控制,其他url可直接访问。)当一个请求的url匹配其中之一后,才会进入这个过滤器链。进入过滤器链后,匹配 /api1/order/**的请求全部需要认证后才能访问,而匹配/api1/address/bejing/**的请求可以直接访问

@Configuration
@EnableWebSecurity
public class MySecurityConfiguration extends WebSecurityConfigurerAdapter {




@Override
protected void configure(HttpSecurity http) throws Exception {

http.requestMatchers()
.antMatchers("/api1/order/**","/api1/address/**")
.and().authorizeRequests()
.antMatchers("/api1/order/**").authenticated()
.antMatchers("/api1/address/beijing/**").permitAll()
.and()
.csrf().disable();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
AuthenticationManager manager = super.authenticationManagerBean();
return manager;
}
}
二、ResourceServerConfigurerAdapter与WebSecurityConfigurerAdapt

1.ResourceServerConfigurerAdapter是用于当使用spring的oath2时, 配置哪些url要进行oauth2认证

2.WebSecurityConfigurerAdapter是用于当前这个项目本身的访问控制。

3.ResourceServerConfigurerAdapter与WebSecurityConfigurerAdapter都有一个相同的方法,配置url的访问安全控制策略:

public void configure(HttpSecurity http) throws Exception {}
如果在这个方法中配置了相同的url访问控制,会发现ResourceServerConfigurerAdapter配置控制策略生效,而WebSecurityConfigurerAdapter配置的策略不起作用。是因为ResourceServerConfigurerAdapter的order值小,优先级高。所以ResourceServerConfigurerAdapter起作用。
————————————————
版权声明:本文为CSDN博主「join_null」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/join_null/article/details/119390280

posted @ 2022-04-22 13:53  开顺  阅读(825)  评论(0编辑  收藏  举报