上一篇 Spring Security 基础配置: http://t.csdn.cn/m9oq5
在上文Spring Boot 学习之路之 Spring Security(一)中完成了有关于用Securety完成登录认证以及授权的基本配置
接下来本文中引入mybatis,完成真实的用户登录,并根据用户名匹配权限。
准备数据库:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for wx_permission
-- ----------------------------
DROP TABLE IF EXISTS `wx_permission`;
CREATE TABLE `wx_permission` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`pid` bigint(20) NULL DEFAULT NULL COMMENT '父级权限id',
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '名称',
`value` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '权限值',
`icon` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '图标',
`type` int(1) NULL DEFAULT NULL COMMENT '权限类型:0->目录;1->菜单;2->按钮(接口绑定权限)',
`uri` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '前端资源路径',
`status` int(1) NULL DEFAULT NULL COMMENT '启用状态;0->禁用;1->启用',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
`sort` int(11) NULL DEFAULT NULL COMMENT '排序',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 19 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '后台用户权限表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of wx_permission
-- ----------------------------
INSERT INTO `wx_permission` VALUES (1, 0, '商品', '', NULL, 0, NULL, 1, '2020-07-29 16:15:14', 0);
INSERT INTO `wx_permission` VALUES (2, 1, '商品列表', 'wx:product:read', NULL, 1, '/wx/product/index', 1, '2020-07-29 16:17:01', 0);
INSERT INTO `wx_permission` VALUES (3, 1, '添加商品', 'wx:product:create', NULL, 1, '/wx/product/add', 1, '2020-07-29 16:18:51', 0);
INSERT INTO `wx_permission` VALUES (4, 1, '商品分类', 'wx:productCategory:read', NULL, 1, '/wx/productCate/index', 1, '2020-07-29 16:23:07', 0);
INSERT INTO `wx_permission` VALUES (5, 1, '商品类型', 'wx:productAttribute:read', NULL, 1, '/wx/productAttr/index', 1, '2020-07-29 16:24:43', 0);
INSERT INTO `wx_permission` VALUES (6, 1, '品牌管理', 'wx:brand:read', NULL, 1, '/wx/brand/index', 1, '2020-07-29 16:25:45', 0);
INSERT INTO `wx_permission` VALUES (7, 2, '编辑商品', 'wx:product:update', NULL, 2, '/wx/product/updateProduct', 1, '2020-07-29 16:34:23', 0);
INSERT INTO `wx_permission` VALUES (8, 2, '删除商品', 'wx:product:delete', NULL, 2, '/wx/product/delete', 1, '2020-07-29 16:38:33', 0);
INSERT INTO `wx_permission` VALUES (9, 4, '添加商品分类', 'wx:productCategory:create', NULL, 2, '/wx/productCate/create', 1, '2020-07-29 16:43:23', 0);
INSERT INTO `wx_permission` VALUES (10, 4, '修改商品分类', 'wx:productCategory:update', NULL, 2, '/wx/productCate/update', 1, '2020-07-29 16:43:55', 0);
INSERT INTO `wx_permission` VALUES (11, 4, '删除商品分类', 'wx:productCategory:delete', NULL, 2, '/wx/productAttr/delete', 1, '2020-07-29 16:44:38', 0);
INSERT INTO `wx_permission` VALUES (12, 5, '添加商品类型', 'wx:productAttribute:create', NULL, 2, '/wx/productAttr/create', 1, '2020-07-29 16:45:25', 0);
INSERT INTO `wx_permission` VALUES (13, 5, '修改商品类型', 'wx:productAttribute:update', NULL, 2, '/wx/productAttr/update', 1, '2020-07-29 16:48:08', 0);
INSERT INTO `wx_permission` VALUES (14, 5, '删除商品类型', 'wx:productAttribute:delete', NULL, 2, '/wx/productAttr/delete', 1, '2020-07-29 16:48:44', 0);
INSERT INTO `wx_permission` VALUES (15, 6, '添加品牌', 'wx:brand:create', NULL, 2, '/wx/brand/add', 1, '2020-07-29 16:49:34', 0);
INSERT INTO `wx_permission` VALUES (16, 6, '修改品牌', 'wx:brand:update', NULL, 2, '/wx/brand/update', 1, '2020-07-29 16:50:55', 0);
INSERT INTO `wx_permission` VALUES (17, 6, '删除品牌', 'wx:brand:delete', NULL, 2, '/wx/brand/delete', 1, '2020-07-29 16:50:59', 0);
INSERT INTO `wx_permission` VALUES (18, 0, '首页', '', NULL, 0, NULL, 1, '2020-07-29 16:51:57', 0);
-- ----------------------------
-- Table structure for wx_role
-- ----------------------------
DROP TABLE IF EXISTS `wx_role`;
CREATE TABLE `wx_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '名称',
`description` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '描述',
`admin_count` int(11) NULL DEFAULT NULL COMMENT '后台用户数量',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
`status` int(1) NULL DEFAULT 1 COMMENT '启用状态:0->禁用;1->启用',
`sort` int(11) NULL DEFAULT 0,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '后台用户角色表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of wx_role
-- ----------------------------
INSERT INTO `wx_role` VALUES (1, '商品管理员', '商品管理员', 0, '2020-07-30 15:46:11', 1, 0);
INSERT INTO `wx_role` VALUES (2, '商品分类管理员', '商品分类管理员', 0, '2020-07-30 15:53:45', 1, 0);
INSERT INTO `wx_role` VALUES (3, '商品类型管理员', '商品类型管理员', 0, '2020-07-30 15:53:56', 1, 0);
INSERT INTO `wx_role` VALUES (4, '品牌管理员', '品牌管理员', 0, '2020-07-30 15:54:12', 1, 0);
-- ----------------------------
-- Table structure for wx_role_permission_relation
-- ----------------------------
DROP TABLE IF EXISTS `wx_role_permission_relation`;
CREATE TABLE `wx_role_permission_relation` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`role_id` bigint(20) NULL DEFAULT NULL,
`permission_id` bigint(20) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 18 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '后台用户角色和权限关系表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of wx_role_permission_relation
-- ----------------------------
INSERT INTO `wx_role_permission_relation` VALUES (1, 1, 1);
INSERT INTO `wx_role_permission_relation` VALUES (2, 1, 2);
INSERT INTO `wx_role_permission_relation` VALUES (3, 1, 3);
INSERT INTO `wx_role_permission_relation` VALUES (4, 1, 7);
INSERT INTO `wx_role_permission_relation` VALUES (5, 1, 8);
INSERT INTO `wx_role_permission_relation` VALUES (6, 2, 4);
INSERT INTO `wx_role_permission_relation` VALUES (7, 2, 9);
INSERT INTO `wx_role_permission_relation` VALUES (8, 2, 10);
INSERT INTO `wx_role_permission_relation` VALUES (9, 2, 11);
INSERT INTO `wx_role_permission_relation` VALUES (10, 3, 5);
INSERT INTO `wx_role_permission_relation` VALUES (11, 3, 12);
INSERT INTO `wx_role_permission_relation` VALUES (12, 3, 13);
INSERT INTO `wx_role_permission_relation` VALUES (13, 3, 14);
INSERT INTO `wx_role_permission_relation` VALUES (14, 4, 6);
INSERT INTO `wx_role_permission_relation` VALUES (15, 4, 15);
INSERT INTO `wx_role_permission_relation` VALUES (16, 4, 16);
INSERT INTO `wx_role_permission_relation` VALUES (17, 4, 17);
-- ----------------------------
-- Table structure for wx_user
-- ----------------------------
DROP TABLE IF EXISTS `wx_user`;
CREATE TABLE `wx_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`icon` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '头像',
`email` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱',
`nick_name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称',
`note` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '备注信息',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
`login_time` datetime NULL DEFAULT NULL COMMENT '最后登录时间',
`status` int(1) NULL DEFAULT 1 COMMENT '帐号启用状态:0->禁用;1->启用',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '后台用户表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of wx_user
-- ----------------------------
INSERT INTO `wx_user` VALUES (1, 'test', '$2a$10$NZ5o7r2E.ayT2ZoxgjlI.eJ6OEYqjH7INR/F.mXDbjZJi9HF0YCVG', '/wx/images/20180607/timg.jpg', NULL, '测试账号', NULL, '2020-07-29 13:55:30', '2020-07-29 13:55:39', 1);
INSERT INTO `wx_user` VALUES (2, 'guest', '$2a$10$NZ5o7r2E.ayT2ZoxgjlI.eJ6OEYqjH7INR/F.mXDbjZJi9HF0YCVG', ' ', '[email protected]', '游客', NULL, '2020-08-10 14:57:10', '2020-08-10 14:57:13', 1);
INSERT INTO `wx_user` VALUES (3, 'admin', '$2a$10$NZ5o7r2E.ayT2ZoxgjlI.eJ6OEYqjH7INR/F.mXDbjZJi9HF0YCVG', '/wx/images/20190129/170157_yIl3_1767531.jpg', '[email protected]', '系统管理员', '系统管理员', '2020-07-29 13:32:47', '2020-07-29 15:38:50', 1);
-- ----------------------------
-- Table structure for wx_user_permission_relation
-- ----------------------------
DROP TABLE IF EXISTS `wx_user_permission_relation`;
CREATE TABLE `wx_user_permission_relation` (
`id` bigint(20) NOT NULL,
`user_id` bigint(20) NULL DEFAULT NULL,
`permission_id` bigint(20) NULL DEFAULT NULL,
`type` tinyint(1) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of wx_user_permission_relation
-- ----------------------------
INSERT INTO `wx_user_permission_relation` VALUES (1, 3, 17, -1);
INSERT INTO `wx_user_permission_relation` VALUES (2, 3, 4, 1);
INSERT INTO `wx_user_permission_relation` VALUES (3, 3, 5, 1);
-- ----------------------------
-- Table structure for wx_user_role_relation
-- ----------------------------
DROP TABLE IF EXISTS `wx_user_role_relation`;
CREATE TABLE `wx_user_role_relation` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`admin_id` bigint(20) NULL DEFAULT NULL,
`role_id` bigint(20) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 17 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '后台用户和角色关系表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of wx_user_role_relation
-- ----------------------------
INSERT INTO `wx_user_role_relation` VALUES (1, 2, 1);
INSERT INTO `wx_user_role_relation` VALUES (13, 3, 1);
INSERT INTO `wx_user_role_relation` VALUES (15, 3, 2);
INSERT INTO `wx_user_role_relation` VALUES (16, 3, 4);
SET FOREIGN_KEY_CHECKS = 1;
1、完成controller的编写:
@RestController
public class SecurityController {
@RequestMapping("/hello")
public String hello() {
return "hello springboot !";
}
@PreAuthorize("hasAuthority('wx:product:read')")
@RequestMapping("/product/read")
public String product() {
return "成功访问product里的read资源。。。";
}
@PreAuthorize("hasAuthority('wx:other')")
@RequestMapping("/other")
public String other() {
return "成功访问other资源。。。";
}
}
2、创建用户实体类,并实现UserDetalis接口:
@Data
public class User implements UserDetails {
private Integer id;
private String username;
private String password;
private String icon;
private String email;
private String nickName;
private String note;
private Date createTime;
private Date loginTime;
private Integer status;
private Set extends GrantedAuthority> authorities;
@Override
public Collection extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
if(this.status==null){
return false;
}
return this.status==1;
}
}
3、创建权限实体类,并实现GrantedAuthority接口:
@Data
public class Permission implements GrantedAuthority {
private Integer id;
private Integer pid;
private String name;
private String value;
private String icon;
private Integer type;
private String uri;
private Integer status;
private Date createTime;
private String sort;
@Override
public String getAuthority() {
// 这里返回的内容要和Controller里的@PreAuthorize("hasAuthority('wx:product:read')")匹配
return this.value;
}
}
4、完成UserDao的编写:
@Mapper
public interface UserDao {
List getUserByName(String name);
List getPermissionByUserId(Integer userId);
}
5、完成UserDao.xml的编写(如果不想在yml配置里面写扫描xml文件,记得在resource下面创建多层包时用"/"代替"."):
6、完成UserService的编写:
public interface UserService {
/**
* 根据用户名获取用户对象
* @param name 用户登录名
* @return
*/
User getUserByName(String name);
/**
* 获取指定用户拥有的权限
* @param userId 用户id
* @return
*/
List getPermissionsByUserId(Integer userId);
}
7、完成UserServiceImpl的编写:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User getUserByName(String name) {
// 获取账户名对应的用户对象
List users= userDao.getUserByName(name);
Assert.isTrue(users.size()==1,"您输入的账户不存在,或者有多个相同的账户");
return users.get(0);
}
@Override
public List getPermissionsByUserId(Integer userId) {
// 获取权限
return userDao.getPermissionByUserId(userId);
}
}
8、创建MyUserDetailsService类,并实现UserDetailsService接口:
@Service(value = "myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.getUserByName(username);
List permissionList= userService.getPermissionsByUserId(user.getId());
HashSet permissions = new HashSet<>(permissionList);
user.setAuthorities(permissions);
return user;
}
}
9、创建MySecurityConfig类,并继承WebSecurityConfigurerAdapter类:
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
MyUserDetailsService myUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
// 第一步,当访问的是hello资源时不需要进行验证。
http.authorizeRequests()
.antMatchers("/hello").permitAll() // 放行指定的资源
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.userDetailsService(myUserDetailsService);
}
/**
* 为密码进行加密,这个得有
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
yml配置文件里记得配置datasource
10、启动入口函数,完成测试。
至此,Spring Boot 整合 mybatis 用 Security 实现登录认证以及授权就算完成了,以上代码亲测有效。