自定义认证连接数据库
- 首先创建数据库和用户表
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;
- 导入依赖
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
- 配置数据库
spring:datasource:url: jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=UTF-8&useSSL=falseusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver
- 编辑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 {@Autowiredprivate 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;}}
- 修改自定义的UserDetailsService,从数据库中获取用户
@Service
public class SpringDataUserDetailsService implements UserDetailsService {@AutowiredUserDao userDao;@Overridepublic 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();
return userDetails;}
}
- 启动服务器测试