
- Spring Security 教程
- Spring Security - 首頁
- Spring Security - 簡介
- Spring Security - 架構
- Spring Security - 專案模組
- Spring Security - 環境設定
- Spring Security - 表單登入
- Spring Security - 自定義表單登入
- Spring Security - 登出
- Spring Security - 記住我
- Spring Security - 重定向
- Spring Security - 標籤庫
- Spring Security - XML 配置
- Spring Security - 身份驗證提供程式
- Spring Security - 基本身份驗證
- Spring Security - AuthenticationFailureHandler
- Spring Security - JWT
- Spring Security - 獲取使用者資訊
- Spring Security - Maven
- Spring Security - 預設密碼編碼器
- Spring Security – 密碼編碼
- Spring Security - 方法級別
- Spring Security 有用資源
- Spring Security - 快速指南
- Spring Security - 有用資源
- Spring Security - 討論
Spring Security - XML 配置
在基於 Spring Boot 的專案中,更傾向於使用基於 Java 的配置,但我們也有等效的 XML 配置。在本文中,我們將使用如下所示的基於 XML 的 Spring Security 配置。
<beans:beans //... <http auto-config="true"> <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" /> <intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')"/> </http> <authentication-manager> <authentication-provider> <user-service> <user name="admin" password="{noop}1234" authorities="ROLE_ADMIN" /> </user-service> </authentication-provider> </authentication-manager> <beans:bean id ="passwordEncoder" class = "org.springframework.security.crypto.password.NoOpPasswordEncoder" factory-method = "getInstance"> </beans:bean> </beans:beans>
http − 所有與 Web 相關的名稱空間功能的父元素。在這裡,我們可以配置要攔截哪些 URL、需要哪些許可權、使用哪種型別的登入以及所有此類配置。
auto-config − 將此屬性設定為 true 會自動設定表單登入、基本登入和登出功能。Spring Security 使用標準值和啟用的功能生成它們。
intercept-url − 使用 access 屬性設定我們要保護的 URL 的模式。
access − 它指定允許哪些使用者訪問 pattern 屬性指定的 URL。這是根據使用者的角色和許可權進行的。我們可以為此屬性使用 SPEL。
authentication-manager − <authentication-manager> 用於配置應用程式中的使用者、其密碼和角色。這些使用者將是能夠訪問應用程式受保護部分的使用者,前提是他們擁有適當的角色。<authentication-provider> 將建立一個 DaoAuthenticationProvider bean,而 <user-service> 元素將建立一個 InMemoryDaoImpl。所有 authentication-provider 元素都允許使用者透過向 authentication-manager 提供使用者資訊來進行身份驗證。
password-encoder − 這將註冊一個密碼編碼器 bean。為了簡化這裡,我們使用了 NoOpPasswordEncoder。
為了在 Spring Boot 應用程式中註冊此 security-config.xml,我們可以按如下所示匯入它
@SpringBootApplication @ImportResource("classpath:/spring/spring-security.xml") public class FormloginApplication { public static void main(String[] args) { SpringApplication.run(FormloginApplication.class, args); } }
讓我們開始使用 Spring Security 進行實際程式設計。在開始使用 Spring 框架編寫示例之前,您必須確保已正確設定 Spring 環境,如Spring Security - 環境設定章節中所述。我們還假設您對 Spring Tool Suite IDE 有些瞭解。
現在讓我們繼續編寫一個由 Maven 管理的基於 Spring MVC 的應用程式,該應用程式將要求使用者登入、驗證使用者身份,然後使用 Spring Security 表單登入功能提供登出選項。
使用 Spring Initializr 建立專案
Spring Initializr 是開始 Spring Boot 專案的好方法。它提供了一個易於使用的使用者介面來建立專案、新增依賴項、選擇 Java 執行時等。它生成一個骨架專案結構,下載後可以在 Spring Tool Suite 中匯入,然後我們可以繼續使用現成的專案結構。
我們選擇一個 Maven 專案,將專案命名為 formlogin,Java 版本為 21。添加了以下依賴項:
Spring Web
Spring Security
Spring Boot DevTools

Thymeleaf 是一個 Java 模板引擎。它允許我們快速開發靜態或動態網頁以在瀏覽器中呈現。它具有極高的可擴充套件性,允許我們詳細定義和自定義模板的處理過程。除此之外,我們可以點選此連結瞭解更多關於 Thymeleaf 的資訊。
讓我們繼續生成我們的專案並下載它。然後我們將其解壓到我們選擇的資料夾中,並使用任何 IDE 開啟它。我將使用Spring Tools Suite 4。它可以從https://springframework.tw/tools網站免費下載,並針對 Spring 應用程式進行了最佳化。
包含所有相關依賴項的 pom.xml
讓我們看一下我們的 pom.xml 檔案。它應該看起來類似於以下內容:
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.3.1</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.tutorialspoint.security</groupId> <artifactId>formlogin</artifactId> <version>0.0.1-SNAPSHOT</version> <name>formlogin</name> <description>Demo project for Spring Boot</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>21</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity6</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Spring Security 配置 XML
以下是建立在/src/main/resources/spring/資料夾中的 spring-security.xml 檔案的完整程式碼。
spring-security.xml
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <http auto-config="true"> <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" /> <intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')"/> </http> <authentication-manager> <authentication-provider> <user-service> <user name="admin" password="{noop}1234" authorities="ROLE_ADMIN" /> </user-service> </authentication-provider> </authentication-manager> <beans:bean id ="passwordEncoder" class = "org.springframework.security.crypto.password.NoOpPasswordEncoder" factory-method = "getInstance"> </beans:bean> </beans:beans>
Spring Boot 應用程式
以下是 FormloginApplication 類的內容,我們從中匯入類路徑中的 spring-security.xml。
FormloginApplication.java
package com.tutorialspoint.security.formlogin; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ImportResource; @SpringBootApplication @ImportResource("classpath:/spring/spring-security.xml") public class FormloginApplication { public static void main(String[] args) { SpringApplication.run(FormloginApplication.class, args); } }
控制器類
在這個類中,我們為 "/" 端點、"/admin"(用於此應用程式的索引頁面和管理員頁面)建立了一個對映。
AuthController.java
package com.tutorialspoint.security.formlogin.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class AuthController { @GetMapping("/") public String home() { return "index"; } @GetMapping("/admin") public String admin() { return "admin"; } }
檢視
在/src/main/resources/templates資料夾中建立 index.html,其內容如下,用作主頁。
index.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title> Hello World! </title> </head> <body> <h1 th:inline="text">Hello World!</h1> <a href="/logout" alt="logout">Sign Out</a> </body> <html>
讓我們在/src/main/resources/templates資料夾中建立 admin.html,其內容如下,用作管理員頁面。
admin.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity6"> <head> <title> Hello Admin! </title> </head> <body> <p>Admin Console</p> <a href="/logout" alt="logout">Sign Out</a> </body> <html>
執行應用程式
一旦我們準備好所有元件,讓我們執行應用程式。右鍵單擊專案,選擇以...執行,然後選擇Spring Boot App。
它將啟動應用程式,一旦應用程式啟動,我們可以執行 localhost:8080 來檢查更改。
輸出
現在開啟 localhost:8080,您可以看到我們的登入頁面。
輸入管理員詳細資訊的登入頁面

管理員的主頁
當我們輸入管理員的有效憑據時,它將載入 index.html 作為主頁。

開啟管理員頁面
現在開啟 localhost:8080/admin,您可以看到管理員頁面。

登出
單擊“登出”連結,它將要求登出。

單擊登出按鈕,它將顯示登入頁面。
