Spring Security – permitAll() 和 web.ignoring()

Spring Security
Remote
1
07:19 PM · Nov 29 ,2025

1. 概述

Spring Security 提供多種機制來配置請求模式為未受保護或允許不受限制的訪問。 在本文中,我們將探討兩種常用的方法: permitAll()web.ignoring(),以及它們如何在 Spring Security 中工作。

2. 配置訪問權限,使用 permitAll()

配置 permitAll() 允許在指定路徑上的所有請求通過,而無需禁用安全過濾器。 這確保了 Spring Security 相關功能,如日誌記錄、會話管理和 CSRF 保護等仍然處於活動狀態。

使用 Java 配置,我們可以允許訪問 /login* 路徑:

http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
  authorizationManagerRequestMatcherRegistry
    .requestMatchers("/login*").permitAll()
);

此配置確保 /login* 路徑對所有人都是可訪問的,同時保持安全過濾器處於活動狀態。它尤其適用於登錄頁面,因為某些 Spring Security 功能,如 CSRF 令牌,是必需的。

3. 通過 web.ignoring() 禁用安全過濾器

在Java配置中,我們可以排除安全過濾器鏈對於特定路徑,例如靜態資源:

web.ignoring().antMatchers("/resources/**")

這種方法對於不需要進行安全處理的路徑非常有用,例如提供靜態資產,如圖像、CSS和JavaScript文件。 但是,請注意,Spring Security功能,如日誌記錄或CSRF令牌,將不可在這些路徑上使用。

4. 使用 的注意事項

在使用諸如 這樣的配置時,定義的順序很重要。 必須在通用匹配模式(如“”)之前明確定義特定路徑。

更具體的模式應在更通用的模式之前定義,以確保正確的匹配。 如果在其他模式之前定義了通用模式“”,則會導致應用程序出現錯誤:

Caused by: java.lang.IllegalArgumentException: A universal match pattern ('/**') 
is defined  before other patterns in the filter chain, causing them to be ignored. 
Please check the ordering in your <security:http> namespace or FilterChainProxy bean configuration
	at o.s.s.c.h.DefaultFilterChainValidator.checkPathOrder(DefaultFilterChainValidator.java:49)
	at o.s.s.c.h.DefaultFilterChainValidator.validate(DefaultFilterChainValidator.java:39)

5. 結論

在本教程中,我們討論了使用 Spring Security 允許訪問路徑的選項。我們探討了 permitAll()web.ignoring() 的關鍵差異,並突出了每種方法在最合適的用例和場景中的使用。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.