> 文档中心 > SpringBoot 整合 SpringSecurity——数据库实现

SpringBoot 整合 SpringSecurity——数据库实现


SpringBoot 整合 SpringSecurity 查询数据库实现用户认证

  1. 在数据库中创建 User 表

    SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS = 0;-- ------------------------------ Table structure for user-- ----------------------------DROP TABLE IF EXISTS `user`;CREATE TABLE `user`  (  `id` int(20) NOT NULL AUTO_INCREMENT,  `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,  `pwd` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,  `email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,  `age` int(11) NULL DEFAULT NULL,  `gender` tinyint(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci unsigned zerofill DEFAULT NULL,  PRIMARY KEY (`id`) USING BTREE) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;-- ------------------------------ Records of user-- ----------------------------INSERT INTO `user` VALUES (1, '张三疯', '123654', '133@qq.com', 133, '0');INSERT INTO `user` VALUES (2, '李四', 'abcdef', '1453@qq.com', 12, '0');INSERT INTO `user` VALUES (3, '王五', '987654', '798@qq.com', 23, '0');INSERT INTO `user` VALUES (4, '赵六', '56+897', '789456@qq.com', 35, '0');SET FOREIGN_KEY_CHECKS = 1;
  2. 导入依赖

    <dependencies>    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId>    </dependency>    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>    </dependency>    <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.3</version>    </dependency>    <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId>    </dependency>    <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional>    </dependency>    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope>    </dependency>    <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope>    </dependency></dependencies>
  3. 在 application.yml 中增加数据库配置

    spring:  datasource:    username: root    password: root    url: jdbc:mysql://localhost:3306/mybatis?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai    driver-class-name: com.mysql.cj.jdbc.Driver

    日志

    logging:  level:    root: info    cn.edu.hziee: debug
  4. 创建 User 登录实体类

    package cn.edu.hziee.entity;import com.baomidou.mybatisplus.annotation.TableName;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data@NoArgsConstructor@AllArgsConstructor@TableName("user")public class UserLogin {    private Integer id;    private String name;    private String pwd;}
  5. 创建 UserMapper 接口

    package cn.edu.hziee.mapper;import cn.edu.hziee.entity.User;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import org.springframework.stereotype.Repository;@Repositorypublic interface UserMapper extends BaseMapper<User> {}
  6. SpringSecurityConfig

    package cn.edu.hziee.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;@Configurationpublic class SpringSecurityConfig extends WebSecurityConfigurerAdapter {    @Bean    public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder();    }}
  7. 新建 UserServiceImpl

    package cn.edu.hziee.service.impl;import cn.edu.hziee.entity.UserLogin;import cn.edu.hziee.mapper.UserMapper;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.AuthorityUtils;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.core.userdetails.UsernameNotFoundException;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.stereotype.Service;import java.util.List;@Service("userDetailsService")public class UserServiceImpl implements UserDetailsService {    @Autowired    private UserMapper userMapper;    @Autowired    private PasswordEncoder passwordEncoder;    @Override    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { QueryWrapper<UserLogin> wrapper = new QueryWrapper(); wrapper.eq("name",username); UserLogin userLogin = userMapper.selectOne(wrapper); if(userLogin == null){     throw new UsernameNotFoundException("用户名不存在!"); } String password = passwordEncoder.encode(userLogin.getPwd()); List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal"); return new User(username, password, authorities);    }}
  8. 在启动类 SpringSecurityApplication 中增加 @MapperScan() 注解

    package cn.edu.hziee;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@MapperScan("cn.edu.hziee.mapper")public class SpringSecurityApplication {    public static void main(String[] args) { SpringApplication.run(SpringSecurityApplication.class, args);    }}

上一篇:SpringBoot 整合 SpringSecurity——入门
下一篇:SpringBoot 整合 SpringSecurity——自定义登录页面