Spring Security Oauth2.0认证授权

17.Spring Security应用详解-自定义认证-连接数

2020-03-26  本文已影响0人  LANSHENGYANG

连接数据库认证

创建数据库

CREATE DATABASE `user_db` CHARACTER set `utf8` COLLTE `utf8_general_ci`;
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`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

代码实现

spring:
  datasource:
    driver-class-name:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/user_db
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>
@Repository
public class UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    //根据账号查询用户信息
    public UserDto getUserByUsername(String username){
        String sql="select id,username,password,fullname,mobile from t_user where username=?";
        //连接数据库查询用户
        List<UserDto> list = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class));
        if (list!=null && list.size()==1){
            return list.get(0);
        }
        return null;
    }
}

定义UserDetailService

@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //登录账号
        System.out.println("username="+username);
        //根据账号去数据库查询
        UserDto user = userDao.getUserByUsername(username);
        if (user==null){
            //如果用户查不到,返回null,由provider抛出异常
            return null;
        }
        //暂时采用模拟方式
        UserDetails userDetails = User.withUsername(user.getUsername()).password(user.getPassword()).authorities("p1").build();
        return userDetails;
    }
}

WebSecurityConfig配置userDetailsService

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    /* 向DaoAuthenticationProvider提交用户信息 */
}
上一篇下一篇

猜你喜欢

热点阅读