1. 概述
Spring Security 提供多種機制來配置請求模式為未受保護或允許無限制訪問。 在本文中,我們將探討兩種常用的方法:permitAll() 和 web.ignoring(),以及它們在 Spring Security 中的工作原理。
2. 使用 permitAll() 配置訪問權限
使用 <em>permitAll()</em> 配置允許在指定路徑上接收所有請求,同時不會禁用安全過濾器。 這確保了 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. 使用 web.ignoring() 的注意事項
在使用諸如 web.ignoring() 這樣的配置時,定義的順序非常重要。具體的路徑必須在定義之前被明確指定,例如使用通配符“/**”。
更具體的模式應在更通用的模式之前被定義,以確保正確的匹配。 如果通用的模式“/**”在其他模式之前被定義,它將覆蓋它們,導致應用程序出現錯誤:
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() 之間的關鍵差異,並強調了它們各自的使用場景和適用場景。