spring boot整合 spring security之认证从数据库查询

Posted 健康平安的活着

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot整合 spring security之认证从数据库查询相关的知识,希望对你有一定的参考价值。

一 介绍

实际项目中用户信息存储在数据库中,只需要重新定义 UserDetailService 即可实现根据用户账号查询数据库。

二 操作步骤

2.1  初始化脚本

1.新建数据库

 2.新建表

CREATE TABLE `t_user` ( `id` bigint(20) NOT NULL COMMENT '用户id', `username` varchar(64) NOT NULL, `password` varchar(64) NOT NULL, `fullname` varchar(255) NOT NULL COMMENT '用户姓名', `mobile` varchar(11) DEFAULT NULL COMMENT '手机号', PRIMARY KEY (`id`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC

3.新增数据

2.2  使用mybaits实现查询数据库

2.2.1 配置pom

  <!-- 连接数据库mysql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
    <!-- 分页插件 -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper-spring-boot-starter</artifactId>
      <version>1.2.5</version>
    </dependency>
    <!-- alibaba的druid数据库连接池 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.1.9</version>
    </dependency>

2.2.2 配置dao层

package com.ljf.spt.security.dao;

import com.ljf.spt.security.model.UserDto;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserMapper {
    //查找用户名
    public UserDto getUserByUsername(@Param("userName") String username);
    //查找该用户名下的权限
    public List<String> findPermissionsByUserId(@Param("userId") String userId);
}

2.2.3 mapper层

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ljf.spt.security.dao.UserMapper" >
 <!-- 查询用户信息 -->
    <select id="getUserByUsername" resultType="com.ljf.spt.security.model.UserDto" >
		select id,username,password,fullname from t_user where username = #{userName}
	</select>
	<!-- 查询用户信息 -->

</mapper>

2.2.4 application配置文件

#基本配置
server.port=8080
server.servlet.context-path=/spt-security
spring.application.name =springboot-security
#视图
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
#mysql
spring.datasource.name=mysql_test
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#druid相关配置
#监控统计拦截的filters
spring.datasource.druid.filters=stat
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
#基本属性
spring.datasource.druid.url=jdbc:mysql://127.0.0.1:3306/security_db?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
spring.datasource.druid.username=root
spring.datasource.druid.password=root
#配置初始化大小/最小/最大
spring.datasource.druid.initial-size=1
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=20
#获取连接等待超时时间
spring.datasource.druid.max-wait=60000
#间隔多久进行一次检测,检测需要关闭的空闲连接
spring.datasource.druid.time-between-eviction-runs-millis=60000
#一个连接在池中最小生存的时间
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=SELECT 'x'
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
#打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
spring.datasource.druid.pool-prepared-statements=false
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
#mybaits
mybatis.mapper-locations: classpath:mapper/*.xml
mybatis.type-aliases-package: com.ljf.spt.security.model
#pagehelper
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
pagehelper.returnPageInfo=check

2.2.5 service配置

package com.ljf.spt.security.service;

import com.ljf.spt.security.dao.UserMapper;
import com.ljf.spt.security.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
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.stereotype.Service;

import java.util.List;

/**
 * @ClassName: SpringDataUserDetailsService
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2021/08/14 09:44:20 
 * @Version: V1.0
 **/
@Service
public class SpringDataUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //将来连接数据库根据账号查询用户信息
        UserDto userDto = userMapper.getUserByUsername(username);
        if(userDto == null){
            //如果用户查不到,返回null,由provider来抛出异常
            return null;


        }
        //权限
        String [] authoritys={"p1"};
        UserDetails userDetails = User.withUsername(userDto.getUsername()).password(userDto.getPassword()).authorities(authoritys).build();
        return userDetails;
    }
}

2.2.6 启动类加注解

package com.ljf.spt.security;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Hello world!
 *
 */
@SpringBootApplication
@MapperScan("com.ljf.spt.security.dao") //@MapperScan 用户扫描MyBatis的Mapper
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class,args);
        System.out.println("启动完成!!!");
    }
}

2.2.7 security配置类设置加密注解

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
同时注释掉:

 2.2.9 启动访问

http://localhost:8080/spt-security/login-view

 成功后:

以上是关于spring boot整合 spring security之认证从数据库查询的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot如何整合Redis

Spring Boot如何整合Redis

Spring Boot:Spring Boot整合FreeMarker

spring boot 系列之四:spring boot 整合JPA

Spring Boot系列Spring Boot整合持久层

Spring Boot 2.X - Spring Boot整合AMQP之RabbitMQ