14.Spring Boot 3.1.5 集成 Spring Security 進行訪問控制
Spring Security 是一個強大且高度可定制的認證和訪問控制框架,專為基于 Spring 的應用程序設計。它為基于 Java EE 的企業應用程序提供了全面的安全解決方案,包括 Web 應用程序安全和方法級安全性。
Spring Security 的工作流程通常包括以下幾個步驟:
攔截請求:通過過濾器鏈攔截所有進入應用程序的請求。
認證用戶:如果請求需要認證,Spring Security 會引導用戶到登錄頁面,并驗證用戶提供的憑據。
授權訪問:認證成功后,Spring Security 檢查用戶是否有權訪問請求的資源。
處理請求:如果用戶有權限,請求將被處理;否則,用戶將被拒絕訪問。
1. 創建 Spring Boot 項目
- 新建項目:
- 打開 IntelliJ IDEA,選擇
File → New → Project
。 - 選擇
Maven
,填寫項目名稱(如demo
),選擇合適的 JDK 版本(建議 17),點擊Next
。 - 輸入
GroupId
(如com.example
)和ArtifactId
(如demo
),選擇打包方式為jar
,點擊Next
。 - 點擊
Finish
完成項目創建。
- 打開 IntelliJ IDEA,選擇
2. 配置 pom.xml
在 pom.xml
中添加 Spring Boot 3.1.5 父依賴和 Spring Security 依賴:
在 pom.xml 中引入 Spring Security 依賴后,默認情況下會攔截所有請求,但 Spring Security 提供了一些默認配置和機制來處理這些請求。以下是默認行為的詳細說明:
默認攔截行為
攔截所有請求:Spring Security 默認會攔截所有進入應用的 HTTP 請求,要求用戶進行認證后才能訪問受保護的資源。
默認登錄頁面:如果用戶未登錄而嘗試訪問受保護的資源,Spring Security 會自動重定向到默認的登錄頁面(路徑為 /login)。
默認用戶名和密碼:首次啟動應用時,Spring Security 會生成一個默認的用戶名(user)和一個隨機密碼,并在控制臺輸出這些信息。
<?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><groupId>com.example</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</name><description>Demo project for Spring Boot with Spring Security</description><!-- Spring Boot 3.1.5 父依賴 --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.1.5</version><relativePath/> <!-- lookup parent from repository --></parent><properties><java.version>17</java.version> <!-- Spring Boot 3.x 需要 Java 17 --></properties><dependencies><!-- Spring Web 依賴 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring Security 依賴 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency></dependencies><build><plugins><!-- Spring Boot Maven 插件 --><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
3. 創建 Spring Boot 啟動類
在 src/main/java
下創建包(如 com.example.demo
),并創建 DemoApplication.java
:
package com.example.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
4. 創建 Security 配置類
在相同的包下創建 SecurityConfig.java
,用于配置 Spring Security:
package com.example.demo;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
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;/*** Spring Security 配置類* 該類用于配置 Spring Security 的安全規則、用戶認證和授權。*/
@Configuration
@EnableWebSecurity
public class SecurityConfig {/*** 配置安全過濾器鏈,定義請求的安全規則。** @param http HttpSecurity 對象,用于配置 HTTP 請求的安全規則。* @return 配置好的 SecurityFilterChain 對象。* @throws Exception 如果配置過程中出現錯誤。*/@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http// 配置請求的授權規則.authorizeHttpRequests(authorize -> authorize// 允許所有人訪問 /public/** 路徑下的請求.requestMatchers("/public/**").permitAll()// 其他所有請求都需要認證.anyRequest().authenticated())// 配置表單登錄.formLogin(form -> form// 允許所有人訪問登錄頁面.permitAll())// 配置注銷功能.logout(logout -> logout// 允許所有人訪問注銷功能.permitAll());// 返回構建好的 SecurityFilterChainreturn http.build();}/*** 配置用戶詳細信息服務,用于提供用戶認證的信息。* 這里使用內存中的用戶存儲,實際應用中可以替換為數據庫或其他用戶存儲。** @return 配置好的 UserDetailsService 對象。*/@Beanpublic UserDetailsService userDetailsService() {// 創建一個內存中的用戶UserDetails user = User.builder()// 設置用戶名.username("user")// 設置密碼,使用 PasswordEncoder 對密碼進行加密.password(passwordEncoder().encode("password"))// 設置用戶角色.roles("USER")// 構建用戶對象.build();// 返回內存用戶管理器,用于管理用戶信息return new InMemoryUserDetailsManager(user);}/*** 配置密碼編碼器,用于對用戶密碼進行加密和解密。** @return 配置好的 PasswordEncoder 對象。*/@Beanpublic PasswordEncoder passwordEncoder() {// 返回 BCrypt 密碼編碼器return new BCryptPasswordEncoder();}
}
5. 創建控制器
在相同的包下創建 HelloController.java
,提供一個簡單的受保護端點:
package com.example.demo;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@GetMapping("/hello")public String sayHello() {return "Hello, Spring Security!";}@GetMapping("/public/hello")public String sayHelloPublic() {return "Hello, Public!";}
}
6. 運行和測試
- 啟動應用:
- 右鍵點擊
DemoApplication.java
,選擇Run
,或點擊類名旁邊的綠色箭頭。
- 右鍵點擊
- 測試接口:
- 打開瀏覽器,訪問
http://localhost:8080/public/hello
,頁面應返回Hello, Public!
。
- 訪問
http://localhost:8080/hello
,將會被重定向到登錄頁面。
- 使用用戶名
user
和密碼password
登錄,登錄成功后,訪問http://localhost:8080/hello
,頁面應返回Hello, Spring Security!
。
- 打開瀏覽器,訪問
總結
通過以上步驟,已經成功創建了一個簡單的 Spring Boot 應用,并集成了 Spring Security 進行基本的認證和授權。此示例中,創建了一個受保護的端點 /hello
和一個公共端點 /public/hello
。Spring Security 確保只有經過身份驗證的用戶才能訪問受保護的端點。