1. 程式人生 > 其它 >requestMatchers()方法與authorizeRequests()區別,ResourceServerConfigurerAdapter與WebSecurityConfigurerAdapt

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