Spring Security 自定义数据库认证(初尝试)

张开发
2026/4/9 10:13:21 15 分钟阅读

分享文章

Spring Security 自定义数据库认证(初尝试)
Spring Security 自定义数据库认证 学习笔记适配个人实战案例基于Spring Boot 3 Spring Security 6 MyBatis实现从MySQL数据库查询用户完成登录认证一、学习目标掌握 Spring Security 替换默认用户使用数据库用户完成登录认证理解UserDetailsService核心接口的作用学会封装UserDetails用户信息对象解决集成过程中的常见报错空指针、类型转换、返回null等二、基础环境1. 核心依赖!-- Spring Security --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-security/artifactId/dependency!-- Web --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency!-- MyBatis MySQL --dependencygroupIdorg.mybatis.spring.boot/groupIdartifactIdmybatis-spring-boot-starter/artifactIdversion3.0.3/version/dependencydependencygroupIdcom.mysql/groupIdartifactIdmysql-connector-j/artifactIdscoperuntime/scope/dependency2. 配置文件application.yml配置数据库连接无需额外配置Securityspring:datasource:driver-class-name:com.mysql.cj.jdbc.Driverurl:jdbc:mysql://localhost:3306/你的数据库?useSSLfalseusername:rootpassword:你的密码mybatis:mapper-locations:classpath:mapper/*.xml三、核心代码实现1. 数据库实体类Usercom.sy.pojo.User对应数据库user表DatapublicclassUser{privateIntegerid;privateStringusername;privateStringpassword;privateStringrealName;privateStringphone;privateIntegerstatus;privateDatecreateTime;}2. Mapper 层数据查询UserMapper接口MapperpublicinterfaceUserMapper{// 根据用户名查询用户认证核心方法UserfindByUsername(Stringusername);}XML映射文件selectidfindByUsernameresultTypecom.sy.pojo.Userselect * from user where username #{username}/select3. Service 层认证核心UserService接口继承Security核心接口publicinterfaceUserServiceextendsUserDetailsService{}UserServiceImpl实现类ServicepublicclassUserServiceImplimplementsUserService{AutowiredprivateUserMapperuserMapper;/** * Security 认证核心方法根据用户名加载用户信息 */OverridepublicUserDetailsloadUserByUsername(Stringusername)throwsUsernameNotFoundException{// 1. 从数据库查询用户UseruseruserMapper.findByUsername(username);// 2. 用户不存在抛出异常if(usernull){thrownewUsernameNotFoundException(用户不存在);}// 3. 封装为Security要求的UserDetails对象并返回returnUser.withUsername(user.getUsername()).password(user.getPassword()).authorities(AuthorityUtils.NO_AUTHORITIES).build();}}4. Security 配置类配置密码加密器Security强制要求ConfigurationEnableWebSecuritypublicclassSecurityConfig{// 密码加密BCrypt算法BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}}四、认证执行流程用户提交登录表单 → Security 自动拦截调用loadUserByUsername方法 → 根据用户名查数据库返回UserDetails对象 → Security 自动比对密码验证通过 → 登录成功验证失败 → 报错五、实战常见踩坑总结重点报错信息错误原因解决方案userMapper null未加Service / Mapper类上添加Service、Mapper加Mapper类型转换异常自定义User不能直接返回封装为Security的User对象UserDetails returned null方法最后return null必须return userDetails禁止返回null用户名不匹配登录账号和数据库不一致使用正确用户名登录六、核心知识点UserDetailsServiceSecurity认证的核心接口自定义认证必须实现它UserDetailsSecurity规定的用户信息格式必须封装后返回PasswordEncoder密码加密接口必须配置否则无法认证禁止返回nullloadUserByUsername查到用户必须返回对象没查到抛异常

更多文章