首頁  >  文章  >  Java  >  Spring Security 6 中的新 requestMatchers

Spring Security 6 中的新 requestMatchers

WBOY
WBOY原創
2024-07-19 12:18:31706瀏覽

New requestMatchers in Spring Security 6

在 Spring Security 6 中,requestMatchers 方法已取代了已棄用的 antMatchers、mvcMatchers 和 regexMatchers 方法,用於配置基於路徑的存取控制。以下是關於新 requestMatchers 的要點:

在authorizeHttpRequests中使用requestMatchers

HttpSecurity配置中的authorizeHttpRequests方法可讓您配置細粒度的請求匹配以進行存取控制。您可以使用 requestMatchers 方法來指定應允許或驗證哪些請求。例如:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http.authorizeHttpRequests(auth -> auth
        .requestMatchers("/greet").permitAll()
        .anyRequest().authenticated())
        .formLogin()
        .build();
}

此設定允許無需身份驗證即可存取 /greet 端點,同時需要對所有其他請求進行身份驗證。

requestMatchers 與 securityMatchers

有兩個類似的方法:requestMatchers 和 securityMatchers。兩者都根據類別路徑中 Spring MVC 的存在選擇最合適的 RequestMatcher 實作:

  • 如果 Spring MVC 存在,它使用 MvcRequestMatcher
  • 如果 Spring MVC 不存在,則回退到 AntPathRequestMatcher

主要差異是securityMatchers用在WebSecurityCustomizer等地方,而requestMatchers用在authorizeHttpRequests。

選擇正確的匹配器

requestMatchers 方法可讓您根據模式或其他條件來配對請求,而無需依賴特定的匹配器(如 AntPathRequestMatcher 或 RegexRequestMatcher)。這提供了更大的靈活性和更好的預設值。

要使用特定的匹配器,您可以將 RequestMatcher 實作傳遞給 requestMatchers 方法:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http.authorizeHttpRequests(auth -> auth
        .requestMatchers(new AntPathRequestMatcher("/greet")).permitAll()
        .anyRequest().authenticated())
        .formLogin()
        .build();
}

總之,Spring Security 6 中新的 requestMatchers 方法提供了一種更靈活、更安全的方式來配置基於路徑的存取控制,根據應用程式的依賴關係選擇最合適的 RequestMatcher 實作。

以上是Spring Security 6 中的新 requestMatchers的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn