如何在Spring Boot 3中实现JDBC身份认证?求指导
Spring Boot 3 + JDBC 身份认证完整实现指南
标准项目文件夹结构
src/ ├── main/ │ ├── java/ │ │ └── com/ │ │ └── example/ │ │ └── jdbcauth/ │ │ ├── JdbcAuthApplication.java # 项目启动类 │ │ ├── config/ │ │ │ └── SecurityConfig.java # Spring Security核心配置类 │ │ └── controller/ │ │ └── DemoController.java # 测试用接口控制器 │ └── resources/ │ ├── application.properties # 全局配置文件 │ └── schema.sql # 数据库表结构初始化脚本 └── test/ └── java/ └── com/ └── example/ └── jdbcauth/ └── JdbcAuthApplicationTests.java
1. 添加核心依赖
Maven(pom.xml)
<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> <!-- Spring JDBC 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- H2 内存数据库(测试用,可替换为MySQL/PostgreSQL) --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies>
2. 数据库与基础配置(application.properties)
# H2 内存数据库配置 spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= # 启用H2控制台(调试用) spring.h2.console.enabled=true # 禁用Spring Security默认用户(使用自定义JDBC用户) spring.security.user.name= spring.security.user.password=
3. 初始化数据库表结构(schema.sql)
Spring Security JDBC默认要求两张核心表(用户表+权限表),这里直接用官方标准结构:
-- 用户表 CREATE TABLE IF NOT EXISTS users ( username VARCHAR(50) NOT NULL PRIMARY KEY, password VARCHAR(255) NOT NULL, enabled BOOLEAN NOT NULL ); -- 权限表 CREATE TABLE IF NOT EXISTS authorities ( username VARCHAR(50) NOT NULL, authority VARCHAR(50) NOT NULL, PRIMARY KEY (username, authority), FOREIGN KEY (username) REFERENCES users(username) ); -- 插入测试用户(密码为"password",已用BCrypt加密) INSERT INTO users (username, password, enabled) VALUES ('user', '$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW', true); INSERT INTO authorities (username, authority) VALUES ('user', 'ROLE_USER');
4. Spring Security 核心配置(SecurityConfig.java)
Spring Boot 3已弃用WebSecurityConfigurerAdapter,改用SecurityFilterChain和UserDetailsService的新方式:
package com.example.jdbcauth.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.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.JdbcUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; import javax.sql.DataSource; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/h2-console/**").permitAll() // 允许H2控制台无权限访问 .anyRequest().authenticated() // 其余接口需认证 ) .formLogin(form -> form // 启用默认表单登录页 .permitAll() ) .logout(logout -> logout .permitAll() ) .csrf(csrf -> csrf .ignoringRequestMatchers("/h2-console/**") // 禁用H2控制台的CSRF校验 ) .headers(headers -> headers .frameOptions(frame -> frame.sameOrigin()) // 允许H2控制台的iframe加载 ); return http.build(); } @Bean public UserDetailsService userDetailsService(DataSource dataSource) { // 使用Spring Security内置的JDBC用户详情管理器 return new JdbcUserDetailsManager(dataSource); } @Bean public PasswordEncoder passwordEncoder() { // BCrypt密码编码器,Spring Boot 3官方推荐 return new BCryptPasswordEncoder(); } }
5. 测试接口(DemoController.java)
package com.example.jdbcauth.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class DemoController { @GetMapping("/hello") public String hello() { return "Hello, authenticated user!"; } }
6. 启动测试
- 运行
JdbcAuthApplication启动项目 - 访问
http://localhost:8080/hello,会自动跳转到登录页 - 使用测试账号
user/password登录,即可看到接口返回内容 - 访问
http://localhost:8080/h2-console,用配置文件中的连接信息登录,可查看初始化的用户和权限表
内容的提问来源于stack exchange,提问作者Lavínia Beghini
相关产品推荐
相关产品推荐

