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.mzph.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 依赖数据的响应式变化来准确更新视图和…