17.Spring Security应用详解-自定义认证-连接数
2020-03-26 本文已影响0人
LANSHENGYANG
连接数据库认证
- 前边的例子我们是将用户信息存储在内存中,实际项目中用户信息存储在数据库中,本节实现从数据库读取用户信息。根据前边对认证流程研究,只需要重新定义UserDetailService即可实现根据用户账号查询数据库。
创建数据库
- 创建user_db数据库
CREATE DATABASE `user_db` CHARACTER set `utf8` COLLTE `utf8_general_ci`;
- 创建t_user表
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;
代码实现
- 1)定义dataSource
- 在application.yml配置
spring:
datasource:
driver-class-name:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/user_db
- 2)添加依赖
<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>
- 3)定义Dao
- 定义模型类型,在model包定义UserDao
@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包下定义SpringDataUserDetailsService:
@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提交用户信息 */
}