Spring Boot 3.4.3 和 Spring Security 6.4.2 實現基于內存和 MySQL 的用戶認證

在 Web 應用開發中,用戶認證是保障系統安全的基礎需求。Spring Boot 3.4.3 結合 Spring Security 6.4.2 提供了強大的安全框架支持,可以輕松實現基于內存或數據庫的用戶認證功能。本文將詳細介紹如何在 Spring Boot 3.4.3 中集成 Spring Security 6.4.2,通過內存和 MySQL 兩種方式實現用戶認證,并附上完整代碼示例,助你在2025年的項目中快速構建安全的認證系統。


1. Spring Security 簡介
1.1 什么是 Spring Security?

Spring Security 是 Spring 生態中的安全框架,提供認證、授權和防護功能。Spring Security 6.4.2 支持 Lambda 風格的配置,與 Spring Boot 3.4.3 無縫集成,適合現代 Java 開發。

1.2 認證方式
  • 內存認證:將用戶信息存儲在內存中,適合測試或簡單應用。
  • 數據庫認證:通過 MySQL 等數據庫存儲用戶信息,適合生產環境。
1.3 本文目標
  • 實現基于內存的用戶認證。
  • 配置 MySQL 數據庫認證。
  • 提供登錄和受保護接口示例。

2. 項目實戰

以下是基于 Spring Boot 3.4.3 和 Spring Security 6.4.2 實現內存和 MySQL 用戶認證的完整步驟。

2.1 添加 Maven 依賴

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 http://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.4.3</version></parent><groupId>cn.itbeien</groupId><artifactId>springboot-security-auth</artifactId><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><!-- Spring Boot 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><!-- MySQL 和 JPA --><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency></dependencies>
</project>

說明:

  • spring-boot-starter-security:提供認證和授權支持。
  • spring-boot-starter-data-jpamysql-connector-j:用于 MySQL 數據庫集成。
2.2 配置內存認證
Security 配置類
package cn.joyous.config;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.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;@Configuration
@EnableWebSecurity
public class SecurityConfig {@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(auth -> auth.requestMatchers("/public").permitAll() // 公開接口.anyRequest().authenticated() // 其他需認證).formLogin(form -> form.defaultSuccessUrl("/home") // 登錄成功跳轉).logout(logout -> logout.logoutSuccessUrl("/public") // 退出后跳轉);return http.build();}@Beanpublic UserDetailsService userDetailsService() {var user = User.withUsername("admin").password("{noop}123456") // {noop} 表示明文密碼.roles("USER").build();return new InMemoryUserDetailsManager(user);}
}

說明:

  • InMemoryUserDetailsManager:內存存儲用戶。
  • {noop}:不加密密碼,僅用于測試。
2.3 配置 MySQL 認證
數據源配置

application.yml 中配置 MySQL:

spring:datasource:url: jdbc:mysql://localhost:3306/auth_db?useSSL=false&serverTimezone=UTCusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driverjpa:hibernate:ddl-auto: update # 自動建表show-sql: true
用戶實體類
package cn.joyous.entity;import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import lombok.Data;@Entity
@Data
public class User {@Idprivate Long id;private String username;private String password;private String role;
}
用戶 Repository
package cn.joyous.repository;import cn.itbeien.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;/*** @author itbeien*/
public interface UserRepository extends JpaRepository<User, Long> {User findByUsername(String username);
}
自定義 UserDetailsService
package cn.joyous.service;import cn.joyous.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class CustomUserDetailsService implements UserDetailsService {@Autowiredprivate UserRepository userRepository;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {User user = userRepository.findByUsername(username);if (user == null) {throw new UsernameNotFoundException("用戶不存在");}return org.springframework.security.core.userdetails.User.withUsername(user.getUsername()).password(user.getPassword()).roles(user.getRole()).build();}
}
更新 Security 配置
package cn.joyous.config;import cn.joyous.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
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.web.SecurityFilterChain;@Configuration
@EnableWebSecurity
public class SecurityConfig {@Autowiredprivate CustomUserDetailsService userDetailsService;@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(auth -> auth.requestMatchers("/public").permitAll().anyRequest().authenticated()).formLogin(form -> form.defaultSuccessUrl("/home")).logout(logout -> logout.logoutSuccessUrl("/public"));return http.build();}@Beanpublic UserDetailsService userDetailsService() {return userDetailsService;}
}
2.4 創建控制器

提供測試接口:

package cn.joyous.controller;import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HomeController {@GetMapping("/public")public String publicEndpoint() {return "這是一個公開接口";}@GetMapping("/home")public String home(@AuthenticationPrincipal UserDetails userDetails) {return "歡迎, " + userDetails.getUsername() + "!";}
}
2.5 數據庫準備

創建 auth_db 數據庫,插入測試數據:

INSERT INTO user (id, username, password, role) VALUES (1, 'admin', '{noop}123456', 'USER');
2.6 啟動與測試
  1. 啟動 Spring Boot 應用。
  2. 訪問 http://localhost:8080/public,無需登錄。
  3. 訪問 http://localhost:8080/home,跳轉到登錄頁。
  4. 輸入 admin123456,登錄后顯示歡迎信息。

3. 進階功能(可選)
  1. 密碼加密
    使用 BCrypt 加密密碼:

    @Bean
    public PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();
    }
    

    更新用戶密碼為加密值:

    INSERT INTO user (id, username, password, role) VALUES (1, 'admin', '$2a$10$...', 'USER');
    
  2. 自定義登錄頁
    添加 Thymeleaf 模板 login.html 并配置:

    .formLogin(form -> form.loginPage("/login").permitAll())
    
  3. 角色權限
    配置基于角色的訪問控制:

    .authorizeHttpRequests(auth -> auth.requestMatchers("/admin/**").hasRole("ADMIN").requestMatchers("/user/**").hasRole("USER").anyRequest().authenticated()
    )
    

4. 總結

Spring Boot 3.4.3 和 Spring Security 6.4.2 結合內存和 MySQL 認證,為開發者提供了靈活的安全方案。本文從內存認證到數據庫認證,覆蓋了實現步驟。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/74984.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/74984.shtml
英文地址,請注明出處:http://en.pswp.cn/web/74984.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

HOW - Axios 攔截器特性

目錄 Axios 介紹攔截器特性1. 統一添加 Token&#xff08;請求攔截器&#xff09;2. 處理 401 未授權&#xff08;響應攔截器&#xff09;3. 統一處理錯誤信息&#xff08;響應攔截器&#xff09;4. 請求 Loading 狀態管理5. 自動重試請求&#xff08;如 429 過載&#xff09;6…

JVM核心機制:類加載×字節碼引擎×垃圾回收機制

&#x1f680;前言 “為什么你的Spring應用啟動慢&#xff1f;為什么GC總是突然卡頓&#xff1f;答案藏在JVM的核心機制里&#xff01; 本文將用全流程圖解字節碼案例&#xff0c;帶你穿透三大核心機制&#xff1a; 類加載&#xff1a;雙親委派如何防止惡意代碼入侵&#xff…

coze生成流程圖和思維導圖工作流

需求&#xff1a;通過coze平臺實現生成流程圖和思維導圖&#xff0c;要求支持文檔上傳 最終工作流如下&#xff1a; 入參&#xff1a; 整合用戶需求文件內容的工作流&#xff1a;https://blog.csdn.net/YXWik/article/details/147040071 選擇器分發&#xff0c;不同的類型走…

網絡安全應急響應-文件痕跡排查

在Windows系統的網絡安全應急響應中&#xff0c;文件痕跡排查是識別攻擊行為的關鍵步驟。以下是針對敏感目錄的詳細排查指南及擴展建議&#xff1a; 1. 臨時目錄排查&#xff08;Temp/Tmp&#xff09; 路徑示例&#xff1a; C:\Windows\TempC:\Users\<用戶名>\AppData\L…

SpringBoot集成Redis 靈活使用 TypedTuple 和 DefaultTypedTuple 實現 Redis ZSet 的復雜操作

以下是 Spring Boot 集成 Redis 中 TypedTuple 和 DefaultTypedTuple 的詳細使用說明&#xff0c;包含代碼示例和場景說明&#xff1a; 1. 什么是 TypedTuple 和 DefaultTypedTuple&#xff1f; TypedTuple<T> 接口&#xff1a; 定義了 Redis 中有序集合&#xff08;ZSet…

遞歸實現組合型枚舉(DFS)

從 1~n 這 n 個整數中隨機選出 m 個&#xff0c;輸出所有可能的選擇方案。 輸入格式 兩個整數 n,m,在同一行用空格隔開。 輸出格式 按照從小到大的順序輸出所有方案&#xff0c;每行 1 個。 首先&#xff0c;同一行內的數升序排列&#xff0c;相鄰兩個數用一個空格隔開。…

CentOS 7 鏡像源失效解決方案(2025年)

執行 yum update 報錯&#xff1a; yum install -y yum-utils \ > device-mapper-persistent-data \ > lvm2 --skip-broken 已加載插件&#xff1a;fastestmirror, langpacks Loading mirror speeds from cached hostfile Could not retrieve mirrorlist http://mirror…

vue3 腳手架初始化項目生成文件的介紹

文章目錄 一、介紹二、舉例說明1.src/http/index.js2.src/router/index.js3.src/router/routes.js4.src/stores/index.js5.src/App.vue6.src/main.js7.babel.config.js8.jsconfig.json9.vue.config.js10. .env11.src/mock/index.js12.src/mock/mock-i18n.js13.src/locales/en.j…

ubuntu 20.04 編譯和運行A-LOAM

1.搭建文件目錄和clone代碼 mkdir -p A-LOAM/src cd A-LOAM/src git clone https://github.com/HKUST-Aerial-Robotics/A-LOAM cd .. 2.修改代碼文件 2.1 由于PCL版本1.10&#xff0c;將CMakeLists.txt中的C標準改為14&#xff1a; set(CMAKE_CXX_FLAGS "-stdc14"…

【教程】MacBook 安裝 VSCode 并連接遠程服務器

目錄 需求步驟問題處理 需求 在 Mac 上安裝 VSCode&#xff0c;并連接跳板機和服務器。 步驟 Step1&#xff1a;從VSCode官網&#xff08;https://code.visualstudio.com/download&#xff09;下載安裝包&#xff1a; Step2&#xff1a;下載完成之后&#xff0c;直接雙擊就能…

LabVIEW 長期項目開發

LabVIEW 憑借其圖形化編程的獨特優勢&#xff0c;在工業自動化、測試測量等領域得到了廣泛應用。對于長期運行、持續迭代的 LabVIEW 項目而言&#xff0c;其開發過程涵蓋架構設計、代碼管理、性能優化等多個關鍵環節&#xff0c;每個環節都對項目的成功起著至關重要的作用。下面…

用matlab搭建一個簡單的圖像分類網絡

文章目錄 1、數據集準備2、網絡搭建3、訓練網絡4、測試神經網絡5、進行預測6、完整代碼 1、數據集準備 首先準備一個包含十個數字文件夾的DigitsData&#xff0c;每個數字文件夾里包含1000張對應這個數字的圖片&#xff0c;圖片的尺寸都是 28281 像素的&#xff0c;如下圖所示…

Go 語言語法精講:從 Java 開發者的視角全面掌握

《Go 語言語法精講&#xff1a;從 Java 開發者的視角全面掌握》 一、引言1.1 為什么選擇 Go&#xff1f;1.2 適合 Java 開發者的原因1.3 本文目標 二、Go 語言環境搭建2.1 安裝 Go2.2 推薦 IDE2.3 第一個 Go 程序 三、Go 語言基礎語法3.1 變量與常量3.1.1 聲明變量3.1.2 常量定…

如何選擇優質的安全工具柜:材質、結構與功能的考量

在工業生產和實驗室環境中&#xff0c;安全工具柜是必不可少的設備。它不僅承擔著工具的存儲任務&#xff0c;還直接影響工作環境的安全和效率。那么&#xff0c;如何選擇一個優質的安全工具柜呢&#xff1f;關鍵在于對材質、結構和功能的考量。 01材質&#xff1a;耐用與防腐 …

系統與網絡安全------Windows系統安全(11)

資料整理于網絡資料、書本資料、AI&#xff0c;僅供個人學習參考。 制作U啟動盤 U啟動程序 下載制作U啟程序 Ventoy是一個制作可啟動U盤的開源工具&#xff0c;只需要把ISO等類型的文件拷貝到U盤里面就可以啟動了 同時支持x86LegacyBIOS、x86_64UEFI模式。 支持Windows、L…

【5】搭建k8s集群系列(二進制部署)之安裝master節點組件(kube-controller-manager)

注&#xff1a;承接專欄上一篇文章 一、創建配置文件 cat > /opt/kubernetes/cfg/kube-controller-manager.conf << EOF KUBE_CONTROLLER_MANAGER_OPTS"--logtostderrfalse \\ --v2 \\ --log-dir/opt/kubernetes/logs \\ --leader-electtrue \\ --kubeconfig/op…

C#里第一個WPF程序

WPF程序對界面進行優化,但是比WINFORMS的程序要復雜很多, 并且界面UI基本上不適合拖放,所以需要比較多的時間來布局界面, 產且需要開發人員編寫更多的代碼。 即使如此,在面對誘人的界面表現, 隨著客戶對界面的需求提高,還是需要采用這樣的方式來實現。 界面的樣式采…

createContext+useContext+useReducer組合管理React復雜狀態

createContext、useContext 和 useReducer 的組合是 React 中管理全局狀態的一種常見模式。這種模式非常適合在不引入第三方狀態管理庫&#xff08;如 Redux&#xff09;的情況下&#xff0c;管理復雜的全局狀態。 以下是一個經典的例子&#xff0c;展示如何使用 createContex…

記一次常規的網絡安全滲透測試

目錄&#xff1a; 前言 互聯網突破 第一層內網 第二層內網 總結 前言 上個月根據領導安排&#xff0c;需要到本市一家電視臺進行網絡安全評估測試。通過對內外網進行滲透測試&#xff0c;網絡和安全設備的使用和部署情況&#xff0c;以及網絡安全規章流程出具安全評估報告。本…

el-table,新增、復制數據后,之前的勾選狀態丟失

需要考慮是否為 更新數據的方式不對 如果新增數據的方式是直接替換原數據數組&#xff0c;而不是通過正確的響應式數據更新方式&#xff08;如使用 Vue 的 this.$set 等方法 &#xff09;&#xff0c;也可能導致勾選狀態丟失。 因為 Vue 依賴數據的響應式變化來準確更新視圖和…