Spring Security OAuth2.0(7):自定义认证连接数据库

自定义认证连接数据库

  1. 首先创建数据库和用户表
CREATE TABLE `t_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(64) DEFAULT NULL,
  `password` varchar(64) DEFAULT NULL,
  `fullname` varchar(255) DEFAULT NULL,
  `mobile` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Spring Security OAuth2.0(7):自定义认证连接数据库_第1张图片

  1. 导入依赖
 <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>

  1. 配置数据库
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=UTF-8&useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

  1. 编辑UserDto和UserDao
@Data
public class UserDto {

    private String id;

    private String username;

    private String password;

    private String fullname;

    private String mobile;

    private Set<String> authorities;
}

@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    public UserDto getUserByUsername(String username) {
        String sql = "select id,username,password,fullname from t_user where username=?";
        List<UserDto> query = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class));
        if (null != query && query.size() == 1) {
            return query.get(0);
        }
        return null;
    }

}

  1. 修改自定义的UserDetailsService,从数据库中获取用户
@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    UserDao userDao;

    //根据用户名获取用户的信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDto user = userDao.getUserByUsername(username);
        if (null == user) {
            return null;
        }
        //从数据库中查用户信息
        System.out.println("查询用户username=" + username);
        UserDetails userDetails = User.withUsername(user.getUsername()).password(user.getPassword()).authorities("p1").build();
//        UserDetails userDetails = User.withUsername("xiaowang").password("$2a$10$NcYCXQUjgeCzc2NWWop6s.pz6KCW9QMaLkBYKu34Co38KTJ3ef2jW").authorities("p1").build();
        return userDetails;
    }
}

  1. 启动服务器测试
    Spring Security OAuth2.0(7):自定义认证连接数据库_第2张图片

Spring Security OAuth2.0(7):自定义认证连接数据库_第3张图片

你可能感兴趣的:(spring,security,oAuth2.0,spring,数据库,java)