今日爆肝两章,Spring Security通过数据库完成验证与授权这个东西是比较重要的,希望大家能够耐心学完。
运行环境:JDK8
开发工具(IDE):IDEA(2020.2.3)
项目构建:Maven
相关依赖:MyBatis-Plus、SpringBoot
数据库:MySQL
前端框架:Vue2.0
项目类型:前后端分离项目
目前我们需要用到两张表
随意任意数据,这里简单给大家来几条SQL语句
r_role.sql
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for r_role
-- ----------------------------
DROP TABLE IF EXISTS `r_role`;
CREATE TABLE `r_role` (
`id` int(55) NOT NULL AUTO_INCREMENT COMMENT 'id',
`rid` int(55) NULL DEFAULT NULL COMMENT '角色id',
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '名称',
`version` int(55) UNSIGNED NULL DEFAULT NULL COMMENT '版本号',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 12 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of r_role
-- ----------------------------
INSERT INTO `r_role` VALUES (8, 1, 'ROLE_MEAL', 0);
INSERT INTO `r_role` VALUES (9, 1, 'ROLE_STAFF', 0);
INSERT INTO `r_role` VALUES (10, 1, 'ROLE_ADMIN', 0);
INSERT INTO `r_role` VALUES (11, 1, 'ROLE_MAIN', 0);
SET FOREIGN_KEY_CHECKS = 1;
r_user
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for r_users
-- ----------------------------
DROP TABLE IF EXISTS `r_users`;
CREATE TABLE `r_users` (
`uid` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT '用户UUID',
`rid` int(255) NULL DEFAULT NULL COMMENT '用户角色id',
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT '用户名',
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT '密码',
`member_uid` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '会员uid',
`email` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '用户邮箱',
`login_date` datetime NULL DEFAULT NULL COMMENT '登录时间',
`register_date` datetime NULL DEFAULT NULL COMMENT '注册时间',
`phone` bigint(100) NULL DEFAULT NULL COMMENT '手机',
`vochers` decimal(55, 0) NULL DEFAULT NULL COMMENT '礼券数',
`portait` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '头像',
`version` int(255) NULL DEFAULT NULL COMMENT '版本号 乐观锁',
PRIMARY KEY (`uid`) USING BTREE,
UNIQUE INDEX `user_uid`(`uid`) USING BTREE
) ENGINE = MyISAM CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of r_users
-- ----------------------------
INSERT INTO `r_users` VALUES ('8b66ba85-af9a-4cfa-a0a9-122b313633d4', 1, 'Marinda', '1353874', '1231232', '[email protected]', '2021-12-05 00:00:00', '2021-12-05 00:00:00', 13538749476, 0, NULL, 0);
INSERT INTO `r_users` VALUES ('a728faf3-3618-49a3-b5cd-519cd8564996', 2, '456456456', '456456', '1231232', '[email protected]', '2021-12-05 00:00:00', '2021-12-12 00:00:00', 123456, 0, NULL, 0);
SET FOREIGN_KEY_CHECKS = 1;
Entity包下定义Role
、User
并新增相关Mapper映射:UserMapper
、RoleMapper
并新增相关Service服务:UserService
、RoleService
、UserDaoDetailsService
并新增相关Service实现类:UserServiceImpl
、RoleServiceImpl
、UserDaoDetailsServiceImpl
至此,需要的一些相关类和接口已经列举出来了,我们接下来通过图文加代码的实例进行学习。
User.class
/** Users实体类
*
* @Author Marinda
* @Date 2021/11/15
*/
@UserAnnotation
@Data
@TableName("r_users")
public class User {
public User()
{
}
public User(String uid,String memberUid)
{
this.uid = uid;
this.memberUid = memberUid;
}
private int rid;
private String name;
private String password;
private long phone;
private String email;
@TableId(value = "uid",type = IdType.UUID)
private String uid;
@TableField(value = "member_uid")
private String memberUid;
@TableField(value = "login_date")
private String LoginDate;
@TableField(value = "register_date")
private String RegisterDate;
@TableField(value = "vochers")
private BigDecimal vochers;
@TableField(value = "portait")
private String portait;
// 角色列表
private List<Role> roleList;
@Version
private int version;
}
Role.class
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.util.Date;
import java.util.List;
/** 身份实体类
* @Date 2021/11/15
* @Author Marinda
*/
@Data
@TableName("r_role")
public class Role {
@TableId(value = "id",type = IdType.AUTO)
private int id;
// 角色id
private int rid;
private String name;
@Version
private int version;
}
UserMapper
/** 用户mapper
* @date 2021/11/16
* @author Marinda_Speed
*
*/
public interface UserMapper extends BaseMapper<User> {
/**
* 通过名字查询到用户
*
* @param name 的名字
* @return {@link User}
*/
@Select("select * from r_users where name = #{name}")
User selectByName(String name);
}
RoleMapper
/**
* 角色映射器
*
* @author Marinda_Speed
* @date 2022/03/14
*/
public interface RoleMapper extends BaseMapper<Role> {
/**
* 获取指定uuid的用户权限
*
* @param rid rid
* @return {@link List}<{@link Role}>
*/
@Select("select * from r_role where rid= #{rid}")
List<Role> getRoleByUidList(int rid);
}
UserService
/** 用户服务层
*
* @date 2021/11/28
* @author Marinda
*
*/
public interface UserService extends IService<User> {
/** 通过用户名查询该数据
*
*/
User selectByName(String name);
}
RoleService
/** 身份服务层
* @date 2021/12/2
* @author Marinda
* @version 1.0
*
*/
public interface RoleService extends IService<Role> {
/**
* 获取指定uuid的用户权限
*
* @param rid uid
* @return {@link List}<{@link Role}>
*/
List<Role> getRoleByUidList(int rid);
}
UserDaoDetailsService(注意) 我们这里是继承了UserDetailsService接口
public interface UserDaoDetailsService extends UserDetailsService {
}
UserServiceImpl
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{
/**
* 通过用户名查询该数据
*
* @param name
*/
@Override
public User selectByName(String name) {
return baseMapper.selectByName(name);
}
}
RoleServiceImpl
/** 身份服务层实现类
* @date 2021/12/2
* @author Marinda
* @version 1.0
*
*/
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
/**
* 获取指定uuid的用户权限
*
* @param rid rid
* @return {@link List}<{@link Role}>
*/
@Override
public List<Role> getRoleByUidList(int rid) {
return baseMapper.getRoleByUidList(rid);
}
}
UserDaoDetailsServiceImpl(重点)
@Service("userDaoDetailsService")
public class UserDaoDetailsServiceImpl implements UserDaoDetailsService {
// 用户服务
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String s) {
User user = userService.selectByName(s);
if(user == null){
return null;
}
List<SimpleGrantedAuthority> simpleGrantedAuthorityList = new ArrayList<>();
// 通过rid获取
user.setRoleList(roleService.getRoleByUidList(user.getRid()));
for(Role role : user.getRoleList()){{
// 添加进入
simpleGrantedAuthorityList.add(new SimpleGrantedAuthority(role.getName()));
}}
String encodePassword = passwordEncoder.encode(user.getPassword());
return new org.springframework.security.core.userdetails.User(user.getName(),encodePassword,simpleGrantedAuthorityList);
}
}
loadUserByName是UserDetailsService接口的方法,其目的就是通过查询用户名来设置相应的权限,再返回前,我们必须要做一个PasswordEncodeer的密码加密。
有人会有疑问?为什么方法返回的是UserDetails,而我们这返回的是User呢?
User是UserDetails的实现类、这里的User并非我们实体类的User,而是Security的User
还没有结束哦,伙伴们诧异了,怎么写半天没看到我们SecurityConfig有代码呢?
接下来给大家看看一行代码完成数据库账户认证。
跟着我们上节笔记的配置,新增一行代码。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDaoDetailsService userDaoDetailsService;
/**
* 配置验证登录-> 账户以及权限设置
*
* @param auth 身份验证
* @throws Exception 异常
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDaoDetailsService).passwordEncoder(getPwordEncoder());
// 配置用户
auth.inMemoryAuthentication().withUser("admin").password(getPwordEncoder().encode("123123")).roles("main");
auth.inMemoryAuthentication().withUser("user").password(getPwordEncoder().encode("123")).roles("staff");
}
/**
* 拦截器 -> 路径拦截放行或者验证
*
* @param web 网络
* @throws Exception 异常
*/
@Override
public void configure(WebSecurity web) throws Exception {
}
/**
* 拦截器 -> 授权管理
*
* @param http http
* @throws Exception 异常
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 放行/路径不需要授权
http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/main").hasRole("MAIN");
// 开启表单验证
http.formLogin();
}
/**
* 密码编码器
*
* @return {@link PasswordEncoder}
*/
@Bean
BCryptPasswordEncoder getPwordEncoder(){
// 我们使用的是BCryptPasswordEncoder方式
return new BCryptPasswordEncoder();
}
}
用数据库内的User一条用户信息登录,至此完成配置。
看看效果图
有些小伙伴们看下来有点迷糊,到底是咋实现这个功能的呢?
我们梳理一下,第一UserDetailsService 是Spring Securiity完成数据库验证与授权的核心接口,下面拥有一个loadUserByName(String s)
方法,实际上完成该接口,配合User、Role两个表的Service和Mapper完成功能。
今天我们讲解了一下Spring Security的数据库的验证与授权。
感谢你的观看。