spring-security の requestMatchers() を理解する 質問する

spring-security の requestMatchers() を理解する 質問する

私はSpring Securityのコードを勉強しています。インターネットで見つけたこの例を理解したいです1:

http.requestMatchers()
        .antMatchers("/management/**") // (1)
        .and()
        .authorizeRequests() // (2)
        .antMatchers("/management/health")
        .permitAll()
        .antMatchers("/management/info")
        .permitAll()
        .antMatchers("/management/**")
        .hasRole("ACTUATOR")
        .anyRequest().permitAll()
        .and()
        .httpBasic(); (3)

}

この構成が理解できません。なぜこのコードなのか:

http.requestMatchers()
        .antMatchers("/management/**")
        .and() 

.authorizeRequests() の前ですか? (1)

それはどういう意味ですか?

この例を説明していただけますか?

2:2 番目のケースでは、違いは何でしょうか?

http.requestMatchers().antMatchers("/rest2/**")
.and()
.authorizeRequests()
.antMatchers("/rest/v1/test/hello").permitAll()
.antMatchers("/rest/v1/test/**").denyAll()
.and()
.requestMatchers().antMatchers("/rest/**")
.and()
.authorizeRequests()
.antMatchers("/rest/v1/test/hello").permitAll();

requestMatchers() を使用するとどのような影響がありますか?

「/rest/v1/test/hello2」にリクエストを送信すると、401 が返されます。リクエストを拒否するルールが antMatchers("/rest2/**") と一致しないのはなぜですか?

ベストアンサー1

の目的は、requestMatchers()Spring Security 構成が適用されるリクエストを指定することです。

たとえば、 と が 2 つあり、 にのみセキュリティ (具体的には CSRF 保護) を適用する場合"/public""/private""/private"次の構成を追加できます。

http
    .requestMatchers()
        .antMatchers("/private/**")
        .and()
    .csrf();

次に、POST すると"/private"403 応答が返されます。
ただし、POST すると、"/public"セキュリティが適用されていないため、200 が返されます。

authorizeRequestsこれは、の種類を示すものとは別です。アクセスセキュリティが適用されるかどうかではなく、そのエンドポイントに必要なセキュリティです。

あなたが挙げた例1では

http
    .requestMatchers()
        .antMatchers("/management/**")
        .and() 
        ...

セキュリティ設定は にのみ適用される"/management/**"ため、 にリクエストを送信しても"/foo"セキュリティは保護されません。

あなたが挙げた例2では、

http
    .requestMatchers()
        .antMatchers("/rest2/**")
        .and()
    .authorizeRequests()
        .antMatchers("/rest/v1/test/hello").permitAll()
        .antMatchers("/rest/v1/test/**").denyAll()
        .and()
    .requestMatchers()
        .antMatchers("/rest/**")
        .and()
    .authorizeRequests()
        .antMatchers("/rest/v1/test/hello").permitAll();

"/rest/v1/test/hello2"が 401 で応答する理由は、"/rest/**"がリクエスト マッチャー内にあるため、セキュリティ ルール.antMatchers("/rest/v1/test/hello").permitAll()が適用されるからです。
にリクエストを送信した場合"/rest3/v1/test/hello2"、 はどのリクエスト マッチャーにも含まれていないため、 は 200 で応答します"/rest3/**"

おすすめ記事