上一篇 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', '  ', 'guest@qq.com', '游客', 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', 'admin@163.com', '系统管理员', '系统管理员', '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;@Overridepublic Collection<? extends GrantedAuthority> getAuthorities() {return this.authorities;}@Overridepublic String getPassword() {return this.password;}@Overridepublic String getUsername() {return this.username;}@Overridepublic boolean isAccountNonExpired() {return true;}@Overridepublic boolean isAccountNonLocked() {return true;}@Overridepublic boolean isCredentialsNonExpired() {return true;}@Overridepublic 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;@Overridepublic String getAuthority() {// 这里返回的内容要和Controller里的@PreAuthorize("hasAuthority('wx:product:read')")匹配return this.value;}
}

4、完成UserDao的编写:

@Mapper
public interface UserDao {List<User> getUserByName(String name);List<Permission> getPermissionByUserId(Integer userId);
}

5、完成UserDao.xml的编写(如果不想在yml配置里面写扫描xml文件,记得在resource下面创建多层包时用"/"代替"."):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wx.try_security.dao.UserDao"><select id="getUserByName" resultType="com.wx.try_security.entity.User">select * from  wx_user where  username =#{name}</select><select id="getPermissionByUserId" resultType="com.wx.try_security.entity.Permission">
--         SELECT * FROM wx_permission as wxp INNER JOIN per
--         (SELECT permission_id from wx_role_permission_relation as rpr INNER JOIN wx_user_role_relation as urr where
--         rpr.role_id = urr.role_id and urr.admin_id = 3) as per on wxp.id = permission_idselect * from  wx_permission p where p.id in(select rp.permission_id from wx_role_permission_relation rp where rp.role_id  in(select ur.role_id from  wx_user_role_relation ur WHERE ur.admin_id =#{userId})UNIONSELECT up.permission_id  from wx_user_permission_relation up WHERE up.type=1 and up.user_id=#{userId})and p.id not in(SELECT up.permission_id  from wx_user_permission_relation up WHERE up.type=-1 and up.user_id=#{userId})</select>
</mapper>

6、完成UserService的编写:

public interface UserService {/*** 根据用户名获取用户对象* @param name 用户登录名* @return*/User getUserByName(String name);/*** 获取指定用户拥有的权限* @param userId 用户id* @return*/List<Permission> getPermissionsByUserId(Integer userId);
}

7、完成UserServiceImpl的编写:

@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserDao userDao;@Overridepublic User getUserByName(String name) {// 获取账户名对应的用户对象List<User> users= userDao.getUserByName(name);Assert.isTrue(users.size()==1,"您输入的账户不存在,或者有多个相同的账户");return users.get(0);}@Overridepublic List<Permission> getPermissionsByUserId(Integer userId) {// 获取权限return userDao.getPermissionByUserId(userId);}
}

8、创建MyUserDetailsService类,并实现UserDetailsService接口:

@Service(value = "myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {@Autowiredprivate UserService userService;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {User user = userService.getUserByName(username);List<Permission> permissionList= userService.getPermissionsByUserId(user.getId());HashSet<Permission> permissions = new HashSet<>(permissionList);user.setAuthorities(permissions);return user;}
}

9、创建MySecurityConfig类,并继承WebSecurityConfigurerAdapter类:

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {@AutowiredMyUserDetailsService myUserDetailsService;@Overrideprotected void configure(HttpSecurity http) throws Exception {// 第一步,当访问的是hello资源时不需要进行验证。http.authorizeRequests().antMatchers("/hello").permitAll() // 放行指定的资源.anyRequest().authenticated().and().formLogin().and().userDetailsService(myUserDetailsService);}/*** 为密码进行加密,这个得有*/@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}

yml配置文件里记得配置datasource

10、启动入口函数,完成测试。

至此,Spring Boot 整合 mybatis 用 Security 实现登录认证以及授权就算完成了,以上代码亲测有效。

Spring Boot 学习之路之 Spring Security(二)加入mybatis相关推荐

  1. 【Spring Boot学习】日志文件,Spring Boot也会写日记了,这些事你知道嘛 ? ? ?

    前言: 大家好,我是良辰丫,在上一篇文章中我们已经学习了Spring Boot的配置,接下来我们要学习一些日志相关的东西,什么是日志呢?我们慢慢往下看.

  2. spring Boot 学习(七、Spring Boot与开发热部署)

    一.热部署 在开发中我们修改一个Java文件后想看到效果不得不重启应用,这导致大量时间 花费,我们希望不重启应用的情况下,程序可以自动部署(热部署).有以下四 种情况,如何能实现热部署. •1.模板引 ...

  3. Spring Boot 学习之路二 配置文件 application.yml

    一.创建配置文件 如图所示,我们在resources文件夹中新建配置文件application.yml 结构图 二.一些基本配置 server: port: 8090 //配置端口session-ti ...

  4. Spring Boot 学习之路 使用JPA对Girl 操作

    package com.imooc.student; import org.springframework.beans.factory.annotation.Autowired; import org ...

  5. Spring Boot 学习之初遇(一)

    在学习Spring Boot 之前,我们先要知道学习的三要素即WHAT.WHY.HOW.有了这三要素,我们不管学习什么技术都如有神助,而且不会迷茫. 引言 说到Spring,估计会Java的人没有不认 ...

  6. Spring Boot学习笔记-进阶(3)

    文章目录 Spring Boot学习笔记-进阶(3) 一.Spring Boot与缓存 二.Spring Boot与消息 三.Spring Boot与检索 四.Spring Boot与任务 异步任务 ...

  7. Spring Boot学习笔记-基础(2)

    Spring Boot学习笔记-基础(2) Spring Boot 优点: – 快速创建独立运行的Spring项目以及与主流框架集成 – 使用嵌入式的Servlet容器,应用无需打成WAR包 – st ...

  8. Spring Boot学习笔记(1)

    文章目录 Spring Boot学习笔记(1) Spring Boot 整合 JSP Spring Boot HTML Thymeleaf 常用语法 Spring Boot 数据校验 Spring B ...

  9. Spring Boot 学习第一步(搭建初步环境)

    学习一个东西的第一步是要学会如何迅速搭建起来一个可用的环境,也就是demo.这里我选择的开发环境是Eclipse, Maven + Spring Web 项目结构在Eclipse下面的实现 我们在这里 ...

最新文章

  1. TensorFlow里,shape=(?, 120)里的问号是怎么回事呢
  2. DHCP服务器的搭建
  3. Docker 命令终极教程:8步走
  4. html div中的id和class
  5. xcode 写代码没有补全 提示
  6. 0002_20190328_Centos修改系统时间
  7. 前端学习(2871):Vue路由权限『前后端全解析』2
  8. Redis笔记之基本数据结构 字典
  9. matlab怎么定义矩阵变量_MATLAB小技巧及策略制定实例
  10. JMETER 为什么需要分布式
  11. Shell脚本常用判断
  12. [转]远远走来一个绿茶婊
  13. CCF NOI1025 统计奖牌
  14. Origin许可进行延期使用
  15. MySQL数据分析实战-朱元禄-专题视频课程
  16. 跳过wifi认证直接上网
  17. php团购实现,团购网站的设计与实现(PHP,MySQL)(含录像)
  18. c语言图形学三角形平移,MFC怎么对所画几何图形进行旋转、填充、放缩???(急用)【...
  19. Order-Preserving Encoding(OPE 保序加密)
  20. 硬件架构的艺术(四)

热门文章

  1. 每日工作记录——ERROR:Simulator:793 - Unable to elaborate instantiated module work
  2. 【猪八戒】- 2017年在线笔试“叠字问题”
  3. 1、ABP 文档介绍
  4. 【模拟器】华为模拟器eNSP安装注意事项及常见报错处理
  5. div html用法详解,div标签详解
  6. 详解Canvas动画部分
  7. matlab音频信号导入,如何将语音信号导入simulink中
  8. 阿里网易面试送送送命题 —— 微服务架构
  9. 阿尔茨海默病与正常衰老中的脑萎缩研究进展
  10. python通过指定网卡发包_Python选择网卡发包及接收数据包