最新版Spring Security中的路徑匹配方案
Spring Security 是一個(gè)功能強(qiáng)大且可高度定制的安全框架,它提供了一套完整的解決方案,用于保護(hù)基于 Spring 的應(yīng)用程序。在 Spring Security 中,路徑匹配是權(quán)限控制的核心部分,它決定了哪些請(qǐng)求可以訪問(wèn)特定的資源。本文將詳細(xì)介紹 Spring Security 中的路徑匹配策略,并提供相應(yīng)的代碼示例。
在舊版的 Spring Security 中,路徑匹配方法有很多,但是新版 Spring Security 對(duì)這些方法進(jìn)行了統(tǒng)一的封裝,都是調(diào)用 requestMatchers 方法進(jìn)行處理:
public C requestMatchers(RequestMatcher... requestMatchers) {
Assert.state(!this.anyRequestConfigured, "Can't configure requestMatchers after anyRequest");
return chainRequestMatchers(Arrays.asList(requestMatchers));
}
requestMatchers 方法接收一個(gè) RequestMatcher 類型的參數(shù),RequestMatcher 是一個(gè)接口,這個(gè)接口是一個(gè)用來(lái)確定 HTTP 請(qǐng)求是否與給定的模式匹配的工具。這個(gè)接口提供了一種靈活的方式來(lái)定義請(qǐng)求的匹配規(guī)則,從而可以對(duì)不同的請(qǐng)求執(zhí)行不同的安全策略。
所以在新版 Spring Security 中,不同的路徑匹配分方案實(shí)際上就是不同的 RequestMatcher 的實(shí)現(xiàn)類。
1. AntPathRequestMatcher
AntPathRequestMatcher 是 Spring 中最常用的請(qǐng)求匹配器之一,它使用 Ant 風(fēng)格的路徑模式來(lái)匹配請(qǐng)求的 URI。
1.1 什么是 Ant 風(fēng)格的路徑模式
Ant 風(fēng)格的路徑模式(Ant Path Matching)是一種用于資源定位的模式匹配規(guī)則,它源自 Apache Ant 這個(gè) Java 構(gòu)建工具。在 Ant 中,這種模式被用來(lái)指定文件系統(tǒng)中的文件和目錄。由于其簡(jiǎn)單性和靈活性,Ant 風(fēng)格的路徑模式也被其他許多框架和應(yīng)用程序所采用,包括 Spring Security。
Ant 風(fēng)格的路徑模式使用了一些特殊的字符來(lái)表示不同級(jí)別的路徑匹配:
?:匹配任何單個(gè)字符(除了路徑分隔符)。*:匹配任何字符的序列(除了路徑分隔符),但不包括空字符串。**:匹配任何字符的序列,包括空字符串。至少匹配一個(gè)字符的序列,并且可以跨越路徑分隔符。{}:表示一個(gè)通配符的選擇,可以匹配多個(gè)逗號(hào)分隔的模式。例如,{,春夏秋冬}可以匹配任何以春夏秋冬開頭的字符串。[]:在某些實(shí)現(xiàn)中,可以用于匹配括號(hào)內(nèi)的單個(gè)字符。():在某些實(shí)現(xiàn)中,可以用于分組匹配。
在 Spring Security 中,Ant 風(fēng)格的路徑模式通常用于定義 URL 路徑和安全配置之間的映射關(guān)系。例如,你可以使用 Ant 風(fēng)格的路徑模式來(lái)指定哪些 URL 路徑需要特定的權(quán)限或角色。
以下是一些 Ant 風(fēng)格路徑模式的例子:
/users/*:匹配以/users/開始的任何路徑,如/users/123或/users/profile。/users/**:匹配以/users/開始的任何路徑,包括子路徑,如/users/123或/users/profile/picture./users/123:精確匹配/users/123。/users/{id}:雖然這不是 Ant 風(fēng)格的模式,但它展示了路徑參數(shù)匹配,可以匹配/users/123、/users/456等。/files/**.{jpg,png}:匹配/files/下所有以.jpg或.png結(jié)尾的文件路徑,如/files/image1.jpg或/files/folder/image.png。
通過(guò)使用 Ant 風(fēng)格的路徑模式,你可以靈活地定義復(fù)雜的 URL 匹配規(guī)則,以適應(yīng)不同的安全需求。
1.2 基本用法
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
// 創(chuàng)建 AntPathRequestMatcher 實(shí)例
RequestMatcher antMatcher = new AntPathRequestMatcher("/users/**", "GET");
// 使用 matcher 進(jìn)行匹配
boolean isMatch = antMatcher.matches(request);
1.3 通配符
?匹配任何單字符。*匹配任何字符序列(但不包括目錄分隔符)。**匹配任何字符序列,包括目錄分隔符。
// 匹配 /admin 下的任何資源,包括子目錄
RequestMatcher adminMatcher = new AntPathRequestMatcher("/admin/**");
// 匹配 /files 目錄下的任何 HTML 文件
RequestMatcher fileMatcher = new AntPathRequestMatcher("/files/*.{html,htm}", "GET");
2. RegexRequestMatcher
RegexRequestMatcher 使用正則表達(dá)式來(lái)匹配請(qǐng)求的 URI 和 HTTP 方法。
2.1 基本用法
import org.springframework.security.web.util.matcher.RegexRequestMatcher;
// 創(chuàng)建 RegexRequestMatcher 實(shí)例
RequestMatcher regexMatcher = new RegexRequestMatcher("^/api/.*", "GET");
// 使用 matcher 進(jìn)行匹配
boolean isMatch = regexMatcher.matches(request);
2.2 使用正則表達(dá)式
// 匹配任何以 /api 開頭的 URI
RequestMatcher apiMatcher = new RegexRequestMatcher("^/api/.*");
// 匹配任何 HTTP 方法
RequestMatcher anyMethodMatcher = new RegexRequestMatcher("^/.*", "GET|POST|PUT|DELETE");
2.3 結(jié)合 Spring Security
下面這段代碼,表示攔截所有以 html、css 以及 js 結(jié)尾的請(qǐng)求,這些請(qǐng)求可以直接訪問(wèn):
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a.requestMatchers(new RegexRequestMatcher("^.*\\.(htm|css|js)$","GET")).permitAll())
.formLogin(Customizer.withDefaults())
.csrf(c -> c.disable());
return http.build();
}
}
3. RequestHeaderRequestMatcher
RequestHeaderRequestMatcher 用來(lái)匹配請(qǐng)求頭中的鍵和值。
import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher;
// 創(chuàng)建 RequestHeaderRequestMatcher 實(shí)例
RequestMatcher headerMatcher = new RequestHeaderRequestMatcher("User-Agent", "Mozilla.*");
// 使用 matcher 進(jìn)行匹配
boolean isMatch = headerMatcher.matches(request);
具體到 Spring Security 中,用法如下:
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a.requestMatchers(new RequestHeaderRequestMatcher("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")).permitAll())
.formLogin(Customizer.withDefaults())
.csrf(c -> c.disable());
return http.build();
}
}
4. NegatedRequestMatcher
NegatedRequestMatcher 允許你否定一個(gè)已有的 RequestMatcher 的匹配結(jié)果。
import org.springframework.security.web.util.matcher.NegatedRequestMatcher; // 創(chuàng)建一個(gè) matcher,然后否定它的匹配結(jié)果 RequestMatcher notAdminMatcher = new NegatedRequestMatcher(adminMatcher); // 使用 negated matcher 進(jìn)行匹配 boolean isNotMatch = notAdminMatcher.matches(request);
例如下面這段代碼表示除了 /hello 之外的地址,全都可以直接訪問(wèn):
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a.requestMatchers(new NegatedRequestMatcher(new AntPathRequestMatcher("/hello"))).permitAll())
.formLogin(Customizer.withDefaults())
.csrf(c -> c.disable());
return http.build();
}
}
5. AndRequestMatcher 和 OrRequestMatcher
AndRequestMatcher 和 OrRequestMatcher 分別用來(lái)組合多個(gè) RequestMatcher 實(shí)例,進(jìn)行“與”或“或”的邏輯匹配。
5.1 AndRequestMatcher
import org.springframework.security.web.util.matcher.AndRequestMatcher; // 組合多個(gè) matcher 進(jìn)行“與”匹配 RequestMatcher andMatcher = new AndRequestMatcher(apiMatcher, headerMatcher); // 使用 andMatcher 進(jìn)行匹配 boolean isMatch = andMatcher.matches(request);
5.2 OrRequestMatcher
import org.springframework.security.web.util.matcher.OrRequestMatcher; // 組合多個(gè) matcher 進(jìn)行“或”匹配 RequestMatcher orMatcher = new OrRequestMatcher(adminMatcher, fileMatcher); // 使用 orMatcher 進(jìn)行匹配 boolean isMatch = orMatcher.matches(request);
6. 總結(jié)
Spring 提供了多種 RequestMatcher 實(shí)現(xiàn)類,以滿足不同的請(qǐng)求匹配需求。通過(guò)合理地使用這些匹配器,可以靈活地定義和實(shí)施安全策略。在實(shí)際應(yīng)用中,你可能需要根據(jù)業(yè)務(wù)需求選擇合適的匹配器,并結(jié)合 Spring Security 的配置來(lái)實(shí)現(xiàn)細(xì)粒度的訪問(wèn)控制。
以上就是最新版Spring Security中的路徑匹配方案的詳細(xì)內(nèi)容,更多關(guān)于Spring Security路徑匹配的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
idea使用spring Initializr 快速搭建springboot項(xiàng)目遇到的坑
這篇文章主要介紹了idea使用spring Initializr 快速搭建springboot項(xiàng)目遇到的坑,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11
Java圖形界面之JFrame,JLabel,JButton詳解
這篇文章主要介紹了Java圖形界面之JFrame、JLabel、JButton詳解,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04
Spring Boot項(xiàng)目中結(jié)合MyBatis實(shí)現(xiàn)MySQL的自動(dòng)主從切換功能
這篇文章主要介紹了Spring Boot項(xiàng)目中結(jié)合MyBatis實(shí)現(xiàn)MySQL的自動(dòng)主從切換功能,本文分步驟給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2025-04-04
關(guān)于ScheduledThreadPoolExecutor不執(zhí)行的原因分析
這篇文章主要介紹了關(guān)于ScheduledThreadPoolExecutor不執(zhí)行的原因分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
SpringBoot全局異常攔截與自定義錯(cuò)誤頁(yè)面實(shí)現(xiàn)過(guò)程解讀
本文介紹了SpringBoot中全局異常攔截與自定義錯(cuò)誤頁(yè)面的實(shí)現(xiàn)方法,包括異常的分類、SpringBoot默認(rèn)異常處理機(jī)制、全局異常攔截實(shí)現(xiàn)、自定義錯(cuò)誤頁(yè)面實(shí)現(xiàn)以及兩者的結(jié)合使用,通過(guò)這些技術(shù),可以提高系統(tǒng)的穩(wěn)定性和用戶體驗(yàn)2025-12-12
Mybatis的mapper文件中#和$的區(qū)別示例解析
MyBatis的mapper文件中,#{}和${}是兩種參數(shù)占位符,核心差異在于參數(shù)解析方式、SQL 注入風(fēng)險(xiǎn)、適用場(chǎng)景,以下從底層原理、使用場(chǎng)景、示例等維度詳細(xì)解析,本文介紹Mybatis的mapper文件中#和$的區(qū)別,感興趣的朋友跟隨小編一起看看吧2025-12-12
SpringBoot重啟后,第一次請(qǐng)求接口請(qǐng)求慢的問(wèn)題及解決
這篇文章主要介紹了SpringBoot重啟后,第一次請(qǐng)求接口請(qǐng)求慢的問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
在本地用idea連接虛擬機(jī)上的hbase集群的實(shí)現(xiàn)代碼
這篇文章主要介紹了在本地用idea連接虛擬機(jī)上的hbase集群的實(shí)現(xiàn)代碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10

