
- 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 - 身份驗證失敗處理器
- Spring Security - JWT
- Spring Security - 獲取使用者資訊
- Spring Security - Maven
- Spring Security - 預設密碼編碼器
- Spring Security – 密碼編碼
- Spring Security - 方法級別
- Spring Security 有用資源
- Spring Security - 快速指南
- Spring Security - 有用資源
- Spring Security - 討論
Spring Security - 基本身份驗證
到目前為止,我們已經看到了基於表單的登入,其中使用基於 HTML 的表單進行使用者名稱/密碼身份驗證。我們可以建立我們自己的自定義登入表單,也可以使用 Spring Security 提供的預設登入表單。還有一種方法可以請求使用者名稱/密碼,我們可以要求使用者在 URL 本身使用基本身份驗證傳遞使用者名稱/密碼。
在 Web 瀏覽的情況下,每當使用者請求受保護的資源時,Spring Security 都會檢查請求的身份驗證。如果請求未經身份驗證/授權,則系統將使用如下所示的預設對話方塊向用戶詢問使用者名稱/密碼

Spring Security 提供以下配置來實現基本身份驗證:
protected void configure(HttpSecurity http) throws Exception { http // ... .authorizeHttpRequests(request -> request.anyRequest().authenticated()) .httpBasic(Customizer.withDefaults()) .build(); }
在這裡,我們正在配置 Spring Security,要求使用基本身份驗證機制對每個請求進行身份驗證。
讓我們開始使用 Spring Security 進行實際程式設計。在開始使用 Spring 框架編寫第一個示例之前,您必須確保已正確設定 Spring 環境,如Spring Security - 環境設定章節中所述。我們還假設您對 Spring Tool Suite IDE 有些瞭解。
現在讓我們繼續編寫一個基於 Spring MVC 的應用程式,該應用程式由 Maven 管理,它將要求使用者登入、驗證使用者,然後使用 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 配置類
在我們的 config 包內,我們建立了 WebSecurityConfig 類。我們將使用此類進行安全配置,因此讓我們使用 @Configuration 註解和 @EnableWebSecurity 對其進行註解。這樣,Spring Security 就會知道將此類視為配置類。正如我們所看到的,Spring 使配置應用程式變得非常容易。
WebSecurityConfig
package com.tutorialspoint.security.formlogin.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class WebSecurityConfig { @Bean protected UserDetailsService userDetailsService() { UserDetails user = User.builder() .username("user") .password(passwordEncoder().encode("user123")) .roles("USER") .build(); UserDetails admin = User.builder() .username("admin") .password(passwordEncoder().encode("admin123")) .roles("USER", "ADMIN") .build(); return new InMemoryUserDetailsManager(user, admin); } @Bean protected PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(request -> request.anyRequest().authenticated()) .httpBasic(Customizer.withDefaults()) .build(); } }
配置類詳細資訊
讓我們看看我們的配置類。
首先,我們將使用 userDetailsService() 方法建立一個 UserDetailsService 類的 bean。我們將使用此 bean 來管理此應用程式的使用者。在這裡,為了簡單起見,我們將使用 InMemoryUserDetailsManager 例項來建立使用者。這些使用者以及我們給定的使用者名稱和密碼分別對映到 User 和 Admin 角色。
密碼編碼器
現在,讓我們看看我們的 PasswordEncoder。我們將在這個例子中使用 BCryptPasswordEncoder 例項。因此,在建立使用者時,我們使用 passwordEncoder 來編碼我們的純文字密碼,如下所示:
.password(passwordEncoder().encode("user123"))
Http 安全配置
完成上述步驟後,我們繼續進行下一個配置。在這裡,我們定義了 filterChain 方法。此方法將 HttpSecurity 作為引數。我們將將其配置為使用我們的表單登入和登出功能。
我們可以觀察到所有這些功能都可以在 Spring Security 中使用。讓我們詳細研究以下部分:
http .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(request -> request.anyRequest().authenticated()) .httpBasic(Customizer.withDefaults()) .build();
這裡需要注意幾點:
然後,我們新增需要對所有請求進行身份驗證的配置。
之後,我們使用 Spring Security 的 httpBasic() 功能,如上所述。這使得瀏覽器請求使用者名稱/密碼。對於 REST API,我們可以將身份驗證設定為 Basic Auth,我們將在本節後面看到。
控制器類
在這個類中,為了簡單起見,我們為單個“/”端點建立了應用程式索引頁面的對映。這將重定向到 index.html。
AuthController
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"; } }
檢視
在/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-springsecurity6"> <head> <title> Hello World! </title> </head> <body> <h1 th:inline="text">Hello World!</h1> <a href="/logout" alt="logout">Sign Out</a> </body> <html>
執行應用程式
由於我們已經準備好所有元件,讓我們執行應用程式。右鍵單擊專案,選擇以...方式執行,然後選擇Spring Boot 應用程式。
它將啟動應用程式,一旦應用程式啟動,我們就可以執行 localhost:8080 來檢查更改。
輸出
現在開啟 localhost:8080,您可以看到瀏覽器透過系統對話方塊請求使用者名稱/密碼。
瀏覽器的使用者名稱/密碼對話方塊

輸入無效憑據
如果我們輸入無效憑據,則相同的對話方塊將再次彈出。

使用者的首頁
如果我們輸入使用者的有效憑據,它將載入使用者的首頁

使用 Postman
我們可以使用 Postman 將身份驗證設定為 Basic Auth,設定使用者名稱/密碼,然後發出如下所示的請求

請瀏覽Postman 教程以設定和學習 Postman。