当前位置:   article > 正文

springboot3.0+spring security6+vue3 前后分离之后端部分_spring-security6

spring-security6

描述

 springboot3.0 使用的jdk版本是17 

mysql脚本

  1. /*
  2. Navicat Premium Data Transfer
  3. Source Server : localhost
  4. Source Server Type : MySQL
  5. Source Server Version : 80029 (8.0.29)
  6. Source Host : localhost:3306
  7. Source Schema : sp
  8. Target Server Type : MySQL
  9. Target Server Version : 80029 (8.0.29)
  10. File Encoding : 65001
  11. Date: 19/12/2023 19:23:41
  12. */
  13. SET NAMES utf8mb4;
  14. SET FOREIGN_KEY_CHECKS = 0;
  15. -- ----------------------------
  16. -- Table structure for sys_menu
  17. -- ----------------------------
  18. DROP TABLE IF EXISTS `sys_menu`;
  19. CREATE TABLE `sys_menu` (
  20. `id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
  21. `name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '菜单名称/按钮名称',
  22. `auth` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '权限名称',
  23. `create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
  24. `parent_id` int NULL DEFAULT NULL COMMENT '父级id',
  25. `is_type` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '类型 1:菜单 , 2:按钮',
  26. `pai_xu` int NULL DEFAULT NULL COMMENT '排序序号',
  27. `path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '前端vue 跳转路径',
  28. PRIMARY KEY (`id`) USING BTREE,
  29. INDEX `idx_parent_id`(`parent_id` ASC) USING BTREE,
  30. INDEX `idx_is_type`(`is_type` ASC) USING BTREE,
  31. INDEX `idx_auth`(`auth` ASC) USING BTREE,
  32. INDEX `idx_path`(`path` ASC) USING BTREE
  33. ) ENGINE = InnoDB AUTO_INCREMENT = 34 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '系统菜单/权限表' ROW_FORMAT = Dynamic;
  34. -- ----------------------------
  35. -- Records of sys_menu
  36. -- ----------------------------
  37. INSERT INTO `sys_menu` VALUES (1, '组织管理', 'org', '2023-12-15 05:24:29', 0, '1', 1, '/org');
  38. INSERT INTO `sys_menu` VALUES (2, '组织管理二级菜单', 'org:er', '2023-12-15 05:25:51', 1, '1', 2, '/org/er');
  39. INSERT INTO `sys_menu` VALUES (3, '添加', 'org:er:add', '2023-12-15 05:26:52', 2, '2', 3, NULL);
  40. INSERT INTO `sys_menu` VALUES (4, '修改', 'org:er:edit', '2023-12-15 05:26:52', 2, '2', 4, NULL);
  41. INSERT INTO `sys_menu` VALUES (5, '用户管理', 'user', '2023-12-15 05:29:02', 0, '1', 5, '/user');
  42. INSERT INTO `sys_menu` VALUES (6, '用户管理二级菜单', 'user:er', '2023-12-15 05:29:02', 5, '1', 6, '/user/er');
  43. INSERT INTO `sys_menu` VALUES (7, '添加', 'user:er:add', '2023-12-15 05:26:52', 6, '2', 7, NULL);
  44. INSERT INTO `sys_menu` VALUES (8, '删除', 'user:er:del', '2023-12-15 05:26:52', 6, '2', 8, NULL);
  45. INSERT INTO `sys_menu` VALUES (9, '角色管理', 'role', '2023-12-15 05:29:02', 0, '1', 9, '/role');
  46. INSERT INTO `sys_menu` VALUES (10, '角色管理二级菜单', 'role:er', '2023-12-15 05:29:02', 9, '1', 10, '/role/er');
  47. INSERT INTO `sys_menu` VALUES (11, '添加', 'role:er:add', '2023-12-15 05:26:52', 10, '2', 11, NULL);
  48. INSERT INTO `sys_menu` VALUES (12, '删除', 'role:er:del', '2023-12-15 05:26:52', 10, '2', 12, NULL);
  49. INSERT INTO `sys_menu` VALUES (13, '权限管理', 'auth', '2023-12-15 05:29:02', 0, '1', 13, '/auth');
  50. INSERT INTO `sys_menu` VALUES (14, '权限管理二级菜单', 'auth:er', '2023-12-15 05:29:02', 13, '1', 14, '/auth/er');
  51. INSERT INTO `sys_menu` VALUES (15, '添加一级菜单', 'auth:er:add', '2023-12-15 05:26:52', 14, '2', 15, NULL);
  52. INSERT INTO `sys_menu` VALUES (16, '删除', 'auth:er:del', '2023-12-15 05:26:52', 14, '2', 16, NULL);
  53. INSERT INTO `sys_menu` VALUES (17, '应用管理', 'apply', '2023-12-16 20:43:40', 0, '1', 17, 'apply');
  54. INSERT INTO `sys_menu` VALUES (18, '应用管理二级菜单', 'apply:er', '2023-12-16 20:44:26', 17, '1', 18, '/apply/er');
  55. INSERT INTO `sys_menu` VALUES (19, '添加', 'apply:er:add', '2023-12-16 20:45:26', 18, '2', 19, NULL);
  56. INSERT INTO `sys_menu` VALUES (20, '修改', 'apply:er:edit', '2023-12-16 20:45:24', 18, '2', 20, NULL);
  57. INSERT INTO `sys_menu` VALUES (27, '删除', 'org:er:del', '2023-12-19 02:49:56', 2, '2', 30, NULL);
  58. INSERT INTO `sys_menu` VALUES (28, '分配角色', 'user:er:fp', '2023-12-19 02:51:05', 6, '2', 31, NULL);
  59. INSERT INTO `sys_menu` VALUES (29, '修改', 'role:er:edit', '2023-12-19 02:51:43', 10, '2', 32, NULL);
  60. INSERT INTO `sys_menu` VALUES (30, '分配权限', 'role:er:fp', '2023-12-19 02:52:02', 10, '2', 34, NULL);
  61. INSERT INTO `sys_menu` VALUES (31, '添加二级菜单', 'auth:er:add:sub', '2023-12-19 02:53:32', 14, '2', 35, NULL);
  62. INSERT INTO `sys_menu` VALUES (32, '修改', 'auth:er:edit', '2023-12-19 02:54:00', 14, '2', 37, NULL);
  63. INSERT INTO `sys_menu` VALUES (33, '添加按钮', 'auth:er:btn', '2023-12-19 07:36:36', 14, '2', 41, NULL);
  64. -- ----------------------------
  65. -- Table structure for sys_menu_role
  66. -- ----------------------------
  67. DROP TABLE IF EXISTS `sys_menu_role`;
  68. CREATE TABLE `sys_menu_role` (
  69. `id` int NOT NULL AUTO_INCREMENT,
  70. `role_id` int NULL DEFAULT NULL COMMENT '角色id',
  71. `menu_id` int NULL DEFAULT NULL COMMENT '权限id',
  72. PRIMARY KEY (`id`) USING BTREE,
  73. INDEX `idx_role_id`(`role_id` ASC) USING BTREE,
  74. INDEX `idx_menu_id`(`menu_id` ASC) USING BTREE
  75. ) ENGINE = InnoDB AUTO_INCREMENT = 575 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '权限角色关联表' ROW_FORMAT = Dynamic;
  76. -- ----------------------------
  77. -- Records of sys_menu_role
  78. -- ----------------------------
  79. INSERT INTO `sys_menu_role` VALUES (17, 2, 1);
  80. INSERT INTO `sys_menu_role` VALUES (18, 2, 2);
  81. INSERT INTO `sys_menu_role` VALUES (19, 2, 3);
  82. INSERT INTO `sys_menu_role` VALUES (20, 2, 4);
  83. INSERT INTO `sys_menu_role` VALUES (21, 2, 5);
  84. INSERT INTO `sys_menu_role` VALUES (22, 2, 6);
  85. INSERT INTO `sys_menu_role` VALUES (23, 2, 7);
  86. INSERT INTO `sys_menu_role` VALUES (24, 2, 8);
  87. INSERT INTO `sys_menu_role` VALUES (25, 2, 9);
  88. INSERT INTO `sys_menu_role` VALUES (26, 2, 10);
  89. INSERT INTO `sys_menu_role` VALUES (27, 2, 11);
  90. INSERT INTO `sys_menu_role` VALUES (28, 2, 12);
  91. INSERT INTO `sys_menu_role` VALUES (29, 2, 13);
  92. INSERT INTO `sys_menu_role` VALUES (30, 2, 14);
  93. INSERT INTO `sys_menu_role` VALUES (31, 2, 15);
  94. INSERT INTO `sys_menu_role` VALUES (32, 2, 16);
  95. INSERT INTO `sys_menu_role` VALUES (159, 3, 3);
  96. INSERT INTO `sys_menu_role` VALUES (160, 3, 4);
  97. INSERT INTO `sys_menu_role` VALUES (161, 3, 7);
  98. INSERT INTO `sys_menu_role` VALUES (162, 3, 8);
  99. INSERT INTO `sys_menu_role` VALUES (163, 3, 11);
  100. INSERT INTO `sys_menu_role` VALUES (164, 3, 12);
  101. INSERT INTO `sys_menu_role` VALUES (165, 3, 15);
  102. INSERT INTO `sys_menu_role` VALUES (166, 3, 16);
  103. INSERT INTO `sys_menu_role` VALUES (167, 3, 32);
  104. INSERT INTO `sys_menu_role` VALUES (168, 3, 17);
  105. INSERT INTO `sys_menu_role` VALUES (169, 3, 18);
  106. INSERT INTO `sys_menu_role` VALUES (170, 3, 19);
  107. INSERT INTO `sys_menu_role` VALUES (171, 3, 20);
  108. INSERT INTO `sys_menu_role` VALUES (515, 10, 1);
  109. INSERT INTO `sys_menu_role` VALUES (516, 10, 2);
  110. INSERT INTO `sys_menu_role` VALUES (517, 10, 3);
  111. INSERT INTO `sys_menu_role` VALUES (518, 10, 4);
  112. INSERT INTO `sys_menu_role` VALUES (519, 10, 27);
  113. INSERT INTO `sys_menu_role` VALUES (520, 10, 5);
  114. INSERT INTO `sys_menu_role` VALUES (521, 10, 6);
  115. INSERT INTO `sys_menu_role` VALUES (522, 10, 7);
  116. INSERT INTO `sys_menu_role` VALUES (523, 10, 8);
  117. INSERT INTO `sys_menu_role` VALUES (524, 10, 28);
  118. INSERT INTO `sys_menu_role` VALUES (525, 10, 20);
  119. INSERT INTO `sys_menu_role` VALUES (548, 1, 1);
  120. INSERT INTO `sys_menu_role` VALUES (549, 1, 2);
  121. INSERT INTO `sys_menu_role` VALUES (550, 1, 3);
  122. INSERT INTO `sys_menu_role` VALUES (551, 1, 4);
  123. INSERT INTO `sys_menu_role` VALUES (552, 1, 27);
  124. INSERT INTO `sys_menu_role` VALUES (553, 1, 5);
  125. INSERT INTO `sys_menu_role` VALUES (554, 1, 6);
  126. INSERT INTO `sys_menu_role` VALUES (555, 1, 7);
  127. INSERT INTO `sys_menu_role` VALUES (556, 1, 8);
  128. INSERT INTO `sys_menu_role` VALUES (557, 1, 28);
  129. INSERT INTO `sys_menu_role` VALUES (558, 1, 9);
  130. INSERT INTO `sys_menu_role` VALUES (559, 1, 10);
  131. INSERT INTO `sys_menu_role` VALUES (560, 1, 11);
  132. INSERT INTO `sys_menu_role` VALUES (561, 1, 12);
  133. INSERT INTO `sys_menu_role` VALUES (562, 1, 29);
  134. INSERT INTO `sys_menu_role` VALUES (563, 1, 30);
  135. INSERT INTO `sys_menu_role` VALUES (564, 1, 13);
  136. INSERT INTO `sys_menu_role` VALUES (565, 1, 14);
  137. INSERT INTO `sys_menu_role` VALUES (566, 1, 15);
  138. INSERT INTO `sys_menu_role` VALUES (567, 1, 16);
  139. INSERT INTO `sys_menu_role` VALUES (568, 1, 31);
  140. INSERT INTO `sys_menu_role` VALUES (569, 1, 32);
  141. INSERT INTO `sys_menu_role` VALUES (570, 1, 33);
  142. INSERT INTO `sys_menu_role` VALUES (571, 1, 17);
  143. INSERT INTO `sys_menu_role` VALUES (572, 1, 18);
  144. INSERT INTO `sys_menu_role` VALUES (573, 1, 19);
  145. INSERT INTO `sys_menu_role` VALUES (574, 1, 20);
  146. -- ----------------------------
  147. -- Table structure for sys_role
  148. -- ----------------------------
  149. DROP TABLE IF EXISTS `sys_role`;
  150. CREATE TABLE `sys_role` (
  151. `id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
  152. `role_code` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色编码',
  153. `role_name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色名称',
  154. PRIMARY KEY (`id`) USING BTREE,
  155. INDEX `idx_role_code`(`role_code` ASC) USING BTREE
  156. ) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '角色表' ROW_FORMAT = Dynamic;
  157. -- ----------------------------
  158. -- Records of sys_role
  159. -- ----------------------------
  160. INSERT INTO `sys_role` VALUES (1, 'admin', '管理员');
  161. INSERT INTO `sys_role` VALUES (2, 'jingli', '经理');
  162. INSERT INTO `sys_role` VALUES (3, 'pt', '普通员工');
  163. INSERT INTO `sys_role` VALUES (10, 'caiwu', '财务');
  164. -- ----------------------------
  165. -- Table structure for sys_user
  166. -- ----------------------------
  167. DROP TABLE IF EXISTS `sys_user`;
  168. CREATE TABLE `sys_user` (
  169. `id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
  170. `account` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '账号',
  171. `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '密码',
  172. `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
  173. `create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
  174. PRIMARY KEY (`id`) USING BTREE,
  175. INDEX `idx_account`(`account` ASC) USING BTREE
  176. ) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户表' ROW_FORMAT = Dynamic;
  177. -- ----------------------------
  178. -- Records of sys_user
  179. -- ----------------------------
  180. INSERT INTO `sys_user` VALUES (1, 'zhangsan', '$2a$10$0nZBWnCqPASXP.cnA4vx7.yg3Bdxm4h8hGOZ2MDX25uFLQh/huui.', '张三', '2023-12-15 04:37:51');
  181. INSERT INTO `sys_user` VALUES (2, 'lisi', '$2a$10$0nZBWnCqPASXP.cnA4vx7.yg3Bdxm4h8hGOZ2MDX25uFLQh/huui.', '李四', '2023-12-15 04:38:07');
  182. INSERT INTO `sys_user` VALUES (3, 'zhaoliu', '123456', '赵六', '2023-12-15 04:38:24');
  183. INSERT INTO `sys_user` VALUES (4, 'wangwu', '$2a$10$xw3X/WlHz3hm6GvelIdztO/P1OS4uizN2kgii9Fiqf6rgjZYwR2.i', '王五', '2023-12-18 21:54:38');
  184. INSERT INTO `sys_user` VALUES (5, 'laojiu', '$2a$10$tAOkYkinUU2V7FkgbSTu6e0M2wjaQ2g.oZ0b9X28jndSK0rhfq81G', '老九', '2023-12-18 22:08:46');
  185. INSERT INTO `sys_user` VALUES (7, 'wmz', '$2a$10$bopmg91MtoGac65D3SxZxuxJCb2QCWDzQbOETAbQwuVyp9KpwGA/u', '王麻子', '2023-12-19 19:06:29');
  186. -- ----------------------------
  187. -- Table structure for sys_user_role
  188. -- ----------------------------
  189. DROP TABLE IF EXISTS `sys_user_role`;
  190. CREATE TABLE `sys_user_role` (
  191. `id` int NOT NULL AUTO_INCREMENT,
  192. `role_id` int NULL DEFAULT NULL COMMENT '角色id',
  193. `user_id` int NULL DEFAULT NULL COMMENT '用户id',
  194. PRIMARY KEY (`id`) USING BTREE,
  195. INDEX `idx_role_id`(`role_id` ASC) USING BTREE,
  196. INDEX `idx_user_id`(`user_id` ASC) USING BTREE
  197. ) ENGINE = InnoDB AUTO_INCREMENT = 34 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户角色关联表' ROW_FORMAT = Dynamic;
  198. -- ----------------------------
  199. -- Records of sys_user_role
  200. -- ----------------------------
  201. INSERT INTO `sys_user_role` VALUES (11, 2, 3);
  202. INSERT INTO `sys_user_role` VALUES (12, 3, 3);
  203. INSERT INTO `sys_user_role` VALUES (18, 2, 5);
  204. INSERT INTO `sys_user_role` VALUES (19, 2, 4);
  205. INSERT INTO `sys_user_role` VALUES (20, 3, 4);
  206. INSERT INTO `sys_user_role` VALUES (21, 1, 2);
  207. INSERT INTO `sys_user_role` VALUES (32, 1, 1);
  208. INSERT INTO `sys_user_role` VALUES (33, 10, 7);
  209. SET FOREIGN_KEY_CHECKS = 1;

项目目录

 

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.dmg</groupId>
  6. <artifactId>sp</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <name>sp</name>
  9. <description>sp</description>
  10. <properties>
  11. <java.version>17</java.version>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  14. <spring-boot.version>3.0.2</spring-boot.version>
  15. </properties>
  16. <dependencies>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-web</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-test</artifactId>
  24. <scope>test</scope>
  25. </dependency>
  26. <!--必须引入webflux 否则 WebClient 不显示-->
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-webflux</artifactId>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.springframework.boot</groupId>
  33. <artifactId>spring-boot-starter-security</artifactId>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.projectlombok</groupId>
  37. <artifactId>lombok</artifactId>
  38. <optional>true</optional>
  39. </dependency>
  40. <!-- 添加MyBatisPlus的依赖 -->
  41. <dependency>
  42. <groupId>com.baomidou</groupId>
  43. <artifactId>mybatis-plus-boot-starter</artifactId>
  44. <version>3.5.4.1</version>
  45. </dependency>
  46. <!-- MySQL数据 -->
  47. <dependency>
  48. <groupId>mysql</groupId>
  49. <artifactId>mysql-connector-java</artifactId>
  50. <version>8.0.16</version>
  51. </dependency>
  52. <!-- druid 连接池-->
  53. <dependency>
  54. <groupId>com.alibaba</groupId>
  55. <artifactId>druid</artifactId>
  56. <version>1.1.14</version>
  57. </dependency>
  58. <!--JWT支持-->
  59. <dependency>
  60. <groupId>com.auth0</groupId>
  61. <artifactId>java-jwt</artifactId>
  62. <version>3.8.2</version>
  63. </dependency>
  64. <!--springboot3.0的版本中 mybatis也要3.0 否则报错-->
  65. <dependency>
  66. <groupId>org.mybatis.spring.boot</groupId>
  67. <artifactId>mybatis-spring-boot-starter</artifactId>
  68. <version>3.0.0</version>
  69. </dependency>
  70. </dependencies>
  71. <dependencyManagement>
  72. <dependencies>
  73. <dependency>
  74. <groupId>org.springframework.boot</groupId>
  75. <artifactId>spring-boot-dependencies</artifactId>
  76. <version>${spring-boot.version}</version>
  77. <type>pom</type>
  78. <scope>import</scope>
  79. </dependency>
  80. </dependencies>
  81. </dependencyManagement>
  82. <build>
  83. <plugins>
  84. <plugin>
  85. <groupId>org.apache.maven.plugins</groupId>
  86. <artifactId>maven-compiler-plugin</artifactId>
  87. <version>3.8.1</version>
  88. <configuration>
  89. <source>17</source>
  90. <target>17</target>
  91. <encoding>UTF-8</encoding>
  92. </configuration>
  93. </plugin>
  94. <plugin>
  95. <groupId>org.springframework.boot</groupId>
  96. <artifactId>spring-boot-maven-plugin</artifactId>
  97. <version>${spring-boot.version}</version>
  98. <configuration>
  99. <mainClass>com.dmg.sp.SpApplication</mainClass>
  100. <skip>true</skip>
  101. </configuration>
  102. <executions>
  103. <execution>
  104. <id>repackage</id>
  105. <goals>
  106. <goal>repackage</goal>
  107. </goals>
  108. </execution>
  109. </executions>
  110. </plugin>
  111. </plugins>
  112. </build>
  113. </project>

resources

application.yml

  1. server:
  2. port: 8083
  3. spring:
  4. application:
  5. name: sp
  6. datasource:
  7. driverClassName: com.mysql.cj.jdbc.Driver
  8. type: com.alibaba.druid.pool.DruidDataSource
  9. url: jdbc:mysql://localhost:3306/sp?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=true&allowMultiQueries=true
  10. username: root
  11. password: 123456
  12. mybatis-plus:
  13. configuration:
  14. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  15. mapper-locations: classpath:mapper/*.xml

MenuMapper.xml 

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.dmg.sp.dao.MenuMapper">
  4. <!--删除菜单关联的角色-->
  5. <delete id="deleteRole">
  6. DELETE from sys_menu_role
  7. WHERE menu_id=#{id}
  8. </delete>
  9. <!--根据菜单id集合 获取对应的权限-->
  10. <select id="getAuthList" resultType="com.dmg.sp.entity.Menu">
  11. SELECT id,auth,path from sys_menu
  12. WHERE id in
  13. <foreach item="item" collection="ids" index="index" open="("
  14. separator="," close=")">
  15. #{item}
  16. </foreach>
  17. </select>
  18. <!--获取所有菜单-->
  19. <select id="getMenuList" resultType="com.dmg.sp.entity.Menu">
  20. SELECT * from sys_menu
  21. ORDER BY pai_xu
  22. </select>
  23. <!--查看角色对应的权限-->
  24. <select id="getRoleAuth" resultType="java.lang.String">
  25. SELECT
  26. auth
  27. FROM
  28. sys_menu
  29. WHERE
  30. id IN ( SELECT menu_id FROM sys_menu_role WHERE role_id = #{roleId} )
  31. ORDER BY
  32. pai_xu
  33. </select>
  34. <!--查询用户关联的菜单id-->
  35. <select id="getMenuIdsByUserId" resultType="Integer">
  36. SELECT
  37. menu_id
  38. FROM
  39. sys_menu_role
  40. WHERE
  41. role_id IN ( SELECT role_id FROM sys_user_role WHERE user_id = #{userId} )
  42. </select>
  43. <!--根据菜单id集合查询父级id -->
  44. <select id="getPIdsByIds" resultType="Integer">
  45. SELECT DISTINCT
  46. parent_id
  47. FROM
  48. sys_menu
  49. WHERE
  50. id IN
  51. <foreach item="item" collection="ids" index="index" open="("
  52. separator="," close=")">
  53. #{item}
  54. </foreach>
  55. </select>
  56. </mapper>

RoleMapper.xml 

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.dmg.sp.dao.RoleMapper">
  4. <!--为角色分配权限-->
  5. <insert id="addRoleAuth">
  6. INSERT INTO `sys_menu_role` (`role_id`, `menu_id`)
  7. VALUES
  8. <foreach collection="menuIds" item="item" index="index" separator=",">
  9. (#{roleId},#{item})
  10. </foreach>
  11. </insert>
  12. <!--删除角色关联的用户-->
  13. <delete id="deleteUser">
  14. DELETE from sys_user_role
  15. WHERE role_id=#{id}
  16. </delete>
  17. <!--删除角色关联的权限-->
  18. <delete id="deleteAuth">
  19. DELETE from sys_menu_role
  20. WHERE role_id=#{id}
  21. </delete>
  22. <!--查看用户对应的角色-->
  23. <select id="getUserRole" resultType="com.dmg.sp.entity.Role">
  24. SELECT * from sys_role
  25. WHERE id in(
  26. SELECT role_id from sys_user_role
  27. WHERE user_id=#{userId}
  28. )
  29. </select>
  30. </mapper>

UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.dmg.sp.dao.UserMapper">
  4. <!--为用户分配角色-->
  5. <insert id="addUserRole">
  6. INSERT INTO `sys_user_role` (`role_id`, `user_id`)
  7. VALUES
  8. <foreach collection="roleIds" item="item" index="index" separator=",">
  9. (#{item},#{userId})
  10. </foreach>
  11. </insert>
  12. <!--删除用户关联的角色-->
  13. <delete id="deleteRole">
  14. DELETE from sys_user_role
  15. WHERE user_id=#{id}
  16. </delete>
  17. <!--查看用户对应的角色id-->
  18. <select id="getUserRoleIds" resultType="Integer">
  19. SELECT role_id from sys_user_role
  20. WHERE user_id=#{userId}
  21. </select>
  22. </mapper>

配置类

  1. package com.dmg.sp.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.cors.CorsConfiguration;
  5. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  6. import org.springframework.web.filter.CorsFilter;
  7. import org.springframework.web.servlet.config.annotation.CorsRegistry;
  8. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  9. //解决跨域
  10. @Configuration
  11. public class CorsConfig implements WebMvcConfigurer {
  12. @Override
  13. public void addCorsMappings(CorsRegistry registry) {
  14. //设置允许跨域的域名
  15. registry.addMapping("/**")
  16. //设置允许跨域的域名
  17. .allowedOriginPatterns("*")
  18. //是否允许cookie
  19. .allowCredentials(true)
  20. //设置允许请求的方式
  21. .allowedMethods(new String[]{"GET","POST","PUT","DELETE","OPTIONS"})
  22. //设置允许的请求头
  23. .allowedHeaders("*")
  24. //跨域允许时间
  25. .maxAge(3600);
  26. }
  27. }

  1. package com.dmg.sp.config;
  2. import com.auth0.jwt.interfaces.Claim;
  3. import com.dmg.sp.service.UserService;
  4. import com.dmg.sp.utils.JWTUtil;
  5. import jakarta.servlet.FilterChain;
  6. import jakarta.servlet.ServletException;
  7. import jakarta.servlet.http.HttpServletRequest;
  8. import jakarta.servlet.http.HttpServletResponse;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.http.HttpMethod;
  12. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  13. import org.springframework.security.core.Authentication;
  14. import org.springframework.security.core.context.SecurityContext;
  15. import org.springframework.security.core.context.SecurityContextHolder;
  16. import org.springframework.security.core.userdetails.UserDetails;
  17. import org.springframework.security.web.SecurityFilterChain;
  18. import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
  19. import org.springframework.stereotype.Component;
  20. import org.springframework.util.AntPathMatcher;
  21. import org.springframework.util.StringUtils;
  22. import org.springframework.web.filter.OncePerRequestFilter;
  23. import java.io.IOException;
  24. import java.util.Map;
  25. /**
  26. * 只登陆1次
  27. */
  28. @Slf4j
  29. @Component
  30. public class JwtAuthenticationFilter extends OncePerRequestFilter {
  31. @Autowired
  32. private UserService userService;
  33. /**
  34. * 所有请求的过滤器
  35. * @param request
  36. * @param response
  37. * @param filterChain
  38. * @throws ServletException
  39. * @throws IOException
  40. */
  41. @Override
  42. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
  43. //origin:指定可以访问本项目的IP
  44. String origin = request.getHeader("Origin");
  45. response.setContentType("application/json;charset=UTF-8");
  46. response.setHeader("Access-Control-Allow-Origin", origin);
  47. response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
  48. response.setHeader("Access-Control-Max-Age", "1800");
  49. // 设置 受支持请求标头(自定义 可以访问的请求头 例如:Token)
  50. response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token,Origin,Content-Type,Accept");
  51. // 指示的请求的响应是否可以暴露于该页面。当true值返回时它可以被暴露
  52. response.setHeader("Access-Control-Allow-Credentials", "true");
  53. //如果是OPTIONS请求,让其响应一个 200状态码,说明可以正常访问
  54. if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
  55. response.setStatus(HttpServletResponse.SC_OK);
  56. return;
  57. }
  58. //获取token信息
  59. String header=request.getHeader("Authorization");
  60. log.info("header:{}",header);
  61. //注意Bearer后面还有一个空格
  62. if(StringUtils.isEmpty(header) || !StringUtils.startsWithIgnoreCase(header,"Bearer ")){
  63. //如果请求头是空的 或者 前置没有以Bearer 开头 那么进入下一个过滤器链
  64. filterChain.doFilter(request,response);
  65. return;
  66. }
  67. //把Bearer空格去掉
  68. String jwt=header.substring(7);
  69. //获取token信息 第二个参数是盐值
  70. Map<String, Claim> tokenInfo= JWTUtil.getTokenInfo(jwt,"123456789");
  71. String account=tokenInfo.get("account").asString();
  72. //获取认证信息是否存在
  73. Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  74. if(!StringUtils.isEmpty(account) && auth==null){
  75. //如果账号不为空 并且 认证信息是空的
  76. //获取用户信息
  77. UserDetails userDetails = userService.loadUserByUsername(account);
  78. if(account.equals(userDetails.getUsername())){
  79. //如果用户信息不为空
  80. SecurityContext securityContext=SecurityContextHolder.createEmptyContext();
  81. //创建用户 认证token 对象
  82. UsernamePasswordAuthenticationToken upt=new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
  83. //把web的请求信息 放到Details
  84. upt.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
  85. //把用户信息放到 安全上下文中
  86. securityContext.setAuthentication(upt);
  87. SecurityContextHolder.setContext(securityContext);
  88. }
  89. }
  90. //放行
  91. filterChain.doFilter(request,response);
  92. }
  93. }
  1. package com.dmg.sp.config;
  2. import com.dmg.sp.utils.Result;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import jakarta.servlet.ServletException;
  5. import jakarta.servlet.http.HttpServletRequest;
  6. import jakarta.servlet.http.HttpServletResponse;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.security.authentication.BadCredentialsException;
  9. import org.springframework.security.authentication.InsufficientAuthenticationException;
  10. import org.springframework.security.core.AuthenticationException;
  11. import org.springframework.security.web.AuthenticationEntryPoint;
  12. import org.springframework.stereotype.Component;
  13. import org.springframework.web.util.WebUtils;
  14. import java.io.IOException;
  15. import java.io.PrintWriter;
  16. import java.util.HashMap;
  17. import java.util.Map;
  18. /**
  19. * 我的身份验证入口点
  20. * 没有登陆认证 异常处理器
  21. * @param
  22. * @return
  23. * @throws Exception
  24. */
  25. @Slf4j
  26. @Component
  27. public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
  28. @Override
  29. public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
  30. //返回json格式
  31. response.setContentType("application/json;charset=utf-8");
  32. //没有登陆 直接访问其他接口 就报401
  33. response.setStatus(401);
  34. Result<String> result = Result.error("401", "请先登录");
  35. ObjectMapper objectMapper=new ObjectMapper();
  36. String s=objectMapper.writeValueAsString(result);
  37. //把json数据 写入 返回给前端
  38. PrintWriter writer=response.getWriter();
  39. writer.write(s);
  40. writer.flush();
  41. writer.close();
  42. }
  43. }
  1. package com.dmg.sp.config;
  2. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  3. import com.dmg.sp.dao.MenuMapper;
  4. import com.dmg.sp.entity.Menu;
  5. import com.dmg.sp.service.MenuService;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.http.HttpMethod;
  11. import org.springframework.security.access.AccessDecisionManager;
  12. import org.springframework.security.access.AccessDecisionVoter;
  13. import org.springframework.security.access.vote.AuthenticatedVoter;
  14. import org.springframework.security.access.vote.UnanimousBased;
  15. import org.springframework.security.authentication.AnonymousAuthenticationToken;
  16. import org.springframework.security.authentication.AuthenticationManager;
  17. import org.springframework.security.authorization.AuthorizationDecision;
  18. import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
  19. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  20. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  21. import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
  22. import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
  23. import org.springframework.security.config.http.SessionCreationPolicy;
  24. import org.springframework.security.core.GrantedAuthority;
  25. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  26. import org.springframework.security.crypto.password.PasswordEncoder;
  27. import org.springframework.security.web.SecurityFilterChain;
  28. import org.springframework.security.web.access.expression.WebExpressionVoter;
  29. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  30. import org.springframework.util.AntPathMatcher;
  31. import org.springframework.util.CollectionUtils;
  32. import java.util.ArrayList;
  33. import java.util.Collection;
  34. import java.util.List;
  35. @EnableWebSecurity
  36. @Slf4j
  37. @Configuration
  38. public class SpConfig {
  39. @Autowired
  40. private JwtAuthenticationFilter jwtAuthenticationFilter;
  41. @Autowired
  42. private MyAuthenticationEntryPoint myAuthenticationEntryPoint;
  43. @Autowired
  44. private MenuMapper menuMapper;
  45. //密码加密
  46. @Bean
  47. public PasswordEncoder passwordEncoder(){
  48. return new BCryptPasswordEncoder();
  49. }
  50. //安全过滤器链
  51. @Bean
  52. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  53. //每次都需要认证 不需要session 会话管理策略设置为无状态,这样就可以防止应用程序的会话被劫持攻击。
  54. http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  55. http
  56. //禁用表单登录 前后分离用不上
  57. .formLogin().disable()
  58. //先进行jwt 校验 在进行账号密码登录
  59. .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
  60. //动态拦截所有请求 如果没有匹配上的 那么就拦截
  61. .authorizeHttpRequests(x->x.anyRequest().authenticated())
  62. //没有登录 直接返回异常信息
  63. .exceptionHandling(x->x.authenticationEntryPoint(myAuthenticationEntryPoint))
  64. //关闭csrf
  65. .csrf().disable();
  66. //创建对象
  67. return http.build();
  68. }
  69. //忽略路径 放行路径
  70. @Bean
  71. public WebSecurityCustomizer webSecurityCustomizer(){
  72. //放行登录接口 这样才能登录成功
  73. return x->x.ignoring().requestMatchers("/dengLu");
  74. }
  75. /**
  76. * 把认证管理器注入到容器
  77. * LoginServiceImpl类中 才能使用这个认证接口
  78. * @param config
  79. * @return
  80. * @throws Exception
  81. */
  82. @Bean
  83. public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
  84. return config.getAuthenticationManager();
  85. }
  86. }

控制层

  1. package com.dmg.sp.controller;
  2. import com.dmg.sp.service.LoginService;
  3. import com.dmg.sp.utils.Result;
  4. import com.dmg.sp.vo.LoginVo;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.CrossOrigin;
  8. import org.springframework.web.bind.annotation.PostMapping;
  9. import org.springframework.web.bind.annotation.RequestBody;
  10. import org.springframework.web.bind.annotation.RestController;
  11. @Slf4j
  12. @RestController
  13. public class LoginController {
  14. @Autowired
  15. private LoginService loginService;
  16. /**
  17. * 登录
  18. * @param vo
  19. * @return
  20. */
  21. @PostMapping("/dengLu")
  22. public Result dengLu(@RequestBody LoginVo vo){
  23. return loginService.login(vo);
  24. }
  25. }
  1. package com.dmg.sp.controller;
  2. import com.dmg.sp.entity.Menu;
  3. import com.dmg.sp.entity.MyUserDetails;
  4. import com.dmg.sp.entity.Role;
  5. import com.dmg.sp.service.MenuService;
  6. import com.dmg.sp.utils.Result;
  7. import com.dmg.sp.vo.IdVo;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.security.core.Authentication;
  10. import org.springframework.security.core.GrantedAuthority;
  11. import org.springframework.security.core.context.SecurityContextHolder;
  12. import org.springframework.web.bind.annotation.PostMapping;
  13. import org.springframework.web.bind.annotation.RequestBody;
  14. import org.springframework.web.bind.annotation.RestController;
  15. import java.util.Collection;
  16. import java.util.List;
  17. import java.util.stream.Collectors;
  18. @RestController
  19. public class MenuController {
  20. @Autowired
  21. private MenuService menuService;
  22. /**
  23. * 获取当前登录人的权限
  24. * @return
  25. */
  26. @PostMapping("/getMyAuth")
  27. public Result getMyAuth(){
  28. //从认证信息上下文中 获取用户权限
  29. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  30. MyUserDetails myUserDetails =(MyUserDetails) authentication.getPrincipal();
  31. return Result.success(myUserDetails.getAuthList());
  32. }
  33. /**
  34. * 获取所有菜单和权限(包括按钮)
  35. * @return
  36. */
  37. @PostMapping("/getMenuList")
  38. public Result getMenuList(){
  39. //根据用户id 获取对应的菜单
  40. List<Menu> list=menuService.getMenuList();
  41. return Result.success(list);
  42. }
  43. /**
  44. * 添加菜单
  45. * @return
  46. */
  47. @PostMapping("/addMenu")
  48. public Result addMenu(@RequestBody Menu menu){
  49. menuService.addMenu(menu);
  50. return Result.success();
  51. }
  52. /**
  53. * 修改菜单
  54. * @return
  55. */
  56. @PostMapping("/editMenu")
  57. public Result editMenu(@RequestBody Menu menu){
  58. menuService.editMenu(menu);
  59. return Result.success();
  60. }
  61. /**
  62. * 删除菜单
  63. * @return
  64. */
  65. @PostMapping("/deleteMenu")
  66. public Result deleteMenu(@RequestBody Menu menu){
  67. menuService.deleteMenu(menu.getId());
  68. return Result.success();
  69. }
  70. /**
  71. * 查看菜单详情
  72. * @return
  73. */
  74. @PostMapping("/getMenuById")
  75. public Result getMenuById(@RequestBody Menu menu){
  76. return Result.success(menuService.getMenuById(menu.getId()));
  77. }
  78. /**
  79. * 查看角色对应的权限
  80. * @return
  81. */
  82. @PostMapping("/getRoleAuth")
  83. public Result getRoleAuth(@RequestBody IdVo vo){
  84. return Result.success(menuService.getRoleAuth(vo.getRoleId()));
  85. }
  86. }
  1. package com.dmg.sp.controller;
  2. import com.dmg.sp.entity.Menu;
  3. import com.dmg.sp.entity.MyUserDetails;
  4. import com.dmg.sp.entity.Role;
  5. import com.dmg.sp.service.RoleService;
  6. import com.dmg.sp.utils.Result;
  7. import com.dmg.sp.vo.IdVo;
  8. import com.dmg.sp.vo.RoleAuthVo;
  9. import com.dmg.sp.vo.UserRoleVo;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.security.core.Authentication;
  12. import org.springframework.security.core.context.SecurityContextHolder;
  13. import org.springframework.web.bind.annotation.PostMapping;
  14. import org.springframework.web.bind.annotation.RequestBody;
  15. import org.springframework.web.bind.annotation.RestController;
  16. import java.util.List;
  17. @RestController
  18. public class RoleController {
  19. @Autowired
  20. private RoleService roleService;
  21. /**
  22. * 获取所有角色
  23. * @return
  24. */
  25. @PostMapping("/getRoleList")
  26. public Result getRoleList(){
  27. List<Role> list=roleService.getRoleList();
  28. return Result.success(list);
  29. }
  30. /**
  31. * 添加角色
  32. * @return
  33. */
  34. @PostMapping("/addRole")
  35. public Result addRole(@RequestBody Role role){
  36. roleService.addRole(role);
  37. return Result.success();
  38. }
  39. /**
  40. * 修改角色
  41. * @return
  42. */
  43. @PostMapping("/editRole")
  44. public Result editRole(@RequestBody Role role){
  45. roleService.editRole(role);
  46. return Result.success();
  47. }
  48. /**
  49. * 删除角色
  50. * @return
  51. */
  52. @PostMapping("/deleteRole")
  53. public Result deleteRole(@RequestBody Role role){
  54. roleService.deleteRole(role.getId());
  55. return Result.success();
  56. }
  57. /**
  58. * 查看角色详情
  59. * @return
  60. */
  61. @PostMapping("/getRoleById")
  62. public Result getRoleById(@RequestBody Role role){
  63. return Result.success(roleService.getRoleById(role.getId()));
  64. }
  65. /**
  66. * 查看用户对应的角色
  67. * @return
  68. */
  69. @PostMapping("/getUserRole")
  70. public Result getUserRole(@RequestBody IdVo vo){
  71. return Result.success(roleService.getUserRole(vo.getUserId()));
  72. }
  73. /**
  74. * 为角色分配权限
  75. * @return
  76. */
  77. @PostMapping("/setRoleAuth")
  78. public Result setRoleAuth(@RequestBody RoleAuthVo vo){
  79. roleService.setRoleAuth(vo);
  80. return Result.success();
  81. }
  82. }
  1. package com.dmg.sp.controller;
  2. import com.dmg.sp.entity.MyUserDetails;
  3. import com.dmg.sp.entity.Role;
  4. import com.dmg.sp.entity.User;
  5. import com.dmg.sp.service.RoleService;
  6. import com.dmg.sp.service.SysUserService;
  7. import com.dmg.sp.utils.Result;
  8. import com.dmg.sp.vo.IdVo;
  9. import com.dmg.sp.vo.UserRoleVo;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.security.core.Authentication;
  12. import org.springframework.security.core.context.SecurityContextHolder;
  13. import org.springframework.web.bind.annotation.PostMapping;
  14. import org.springframework.web.bind.annotation.RequestBody;
  15. import org.springframework.web.bind.annotation.RestController;
  16. import java.util.List;
  17. @RestController
  18. public class UserController {
  19. @Autowired
  20. private SysUserService sysUserService;
  21. /**
  22. * 获取所有用户
  23. * @return
  24. */
  25. @PostMapping("/getUserList")
  26. public Result getUserList(){
  27. List<User> list=sysUserService.getUserList();
  28. return Result.success(list);
  29. }
  30. /**
  31. * 为用户分配角色
  32. * @return
  33. */
  34. @PostMapping("/setUserRole")
  35. public Result setUserRole(@RequestBody UserRoleVo vo){
  36. sysUserService.setUserRole(vo);
  37. return Result.success();
  38. }
  39. /**
  40. * 添加用户
  41. * @return
  42. */
  43. @PostMapping("/addUser")
  44. public Result addUser(@RequestBody User user){
  45. sysUserService.addUser(user);
  46. return Result.success();
  47. }
  48. /**
  49. * 获取当前登录人信息
  50. * @return
  51. */
  52. @PostMapping("/getUserInfo")
  53. public Result getUserInfo(){
  54. //从认证信息上下文中 获取用户权限
  55. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  56. MyUserDetails myUserDetails =(MyUserDetails) authentication.getPrincipal();
  57. User user = myUserDetails.getUser();
  58. return Result.success(user);
  59. }
  60. /**
  61. * 查看用户对应的角色id
  62. * @return
  63. */
  64. @PostMapping("/getUserRoleIds")
  65. public Result getUserRoleIds(@RequestBody IdVo vo){
  66. return Result.success(sysUserService.getUserRoleIds(vo.getUserId()));
  67. }
  68. }

dao

  1. package com.dmg.sp.dao;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.dmg.sp.entity.Menu;
  4. import org.apache.ibatis.annotations.Param;
  5. import java.util.List;
  6. public interface MenuMapper extends BaseMapper<Menu> {
  7. /**
  8. * 根据菜单id集合 获取对应的权限
  9. * @param ids
  10. * @return
  11. */
  12. public List<Menu>getAuthList(@Param("ids") List<Integer> ids);
  13. /**
  14. * 获取所有菜单
  15. * @return
  16. */
  17. List<Menu> getMenuList();
  18. /**
  19. * 删除菜单关联的角色
  20. * @return
  21. */
  22. Integer deleteRole(Integer id);
  23. /**
  24. * 查看角色对应的权限
  25. * @return
  26. */
  27. public List<String> getRoleAuth(@Param("roleId") Integer roleId);
  28. /**
  29. * 查询用户关联的菜单id
  30. * @param userId
  31. * @return
  32. */
  33. public List<Integer> getMenuIdsByUserId(@Param("userId") Integer userId);
  34. /**
  35. * 根据菜单id集合查询父级id
  36. * @param ids
  37. * @return
  38. */
  39. public List<Integer> getPIdsByIds(@Param("ids") List<Integer> ids);
  40. }
  1. package com.dmg.sp.dao;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.dmg.sp.entity.Role;
  4. import com.dmg.sp.entity.User;
  5. import org.apache.ibatis.annotations.Param;
  6. import java.util.List;
  7. public interface RoleMapper extends BaseMapper<Role> {
  8. /**
  9. * 删除角色关联的用户
  10. * @param id
  11. * @return
  12. */
  13. Integer deleteUser(@Param("id") Integer id);
  14. /**
  15. * 删除角色关联的权限
  16. * @param id
  17. * @return
  18. */
  19. Integer deleteAuth(@Param("id") Integer id);
  20. /**
  21. * 查看用户对应的角色
  22. * @param userId
  23. * @return
  24. */
  25. public List<Role> getUserRole(@Param("userId") Integer userId);
  26. /**
  27. * 为角色分配权限
  28. * @return
  29. */
  30. public Integer addRoleAuth(@Param("roleId") Integer roleId,
  31. @Param("menuIds") List<Integer> menuIds);
  32. }
  1. package com.dmg.sp.dao;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.dmg.sp.entity.User;
  4. import com.dmg.sp.vo.UserRoleVo;
  5. import org.apache.ibatis.annotations.Mapper;
  6. import org.apache.ibatis.annotations.Param;
  7. import java.util.List;
  8. public interface UserMapper extends BaseMapper<User> {
  9. /**
  10. * 删除用户关联的角色
  11. * @param id
  12. * @return
  13. */
  14. public Integer deleteRole(@Param("id") Integer id);
  15. /**
  16. * 为用户分配角色
  17. * @return
  18. */
  19. public Integer addUserRole(@Param("userId") Integer userId,
  20. @Param("roleIds") List<Integer> roleIds);
  21. /**
  22. * 查看用户对应的角色id
  23. * @return
  24. */
  25. public List<Integer>getUserRoleIds(@Param("userId") Integer userId);
  26. }

entity

  1. package com.dmg.sp.entity;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import com.fasterxml.jackson.annotation.JsonFormat;
  7. import lombok.Data;
  8. import java.util.Date;
  9. import java.util.List;
  10. @Data
  11. @TableName("sys_menu")
  12. public class Menu {
  13. @TableId(type = IdType.AUTO)
  14. private Integer id;
  15. //菜单名称/按钮名称
  16. private String name;
  17. //权限名称
  18. private String auth;
  19. //创建日期
  20. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
  21. private Date createTime;
  22. //父级id
  23. private Integer parentId;
  24. //类型 1:菜单 , 2:按钮
  25. private String isType;
  26. //排序序号
  27. private Integer paiXu;
  28. /**
  29. * 前端vue 跳转路径
  30. */
  31. private String path;
  32. //子集菜单
  33. @TableField(exist = false)
  34. private List<Menu> children;
  35. }
  1. package com.dmg.sp.entity;
  2. import lombok.Data;
  3. import org.springframework.security.core.GrantedAuthority;
  4. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  5. import org.springframework.security.core.userdetails.UserDetails;
  6. import java.util.Arrays;
  7. import java.util.Collection;
  8. import java.util.List;
  9. import java.util.stream.Collectors;
  10. /**
  11. * UserDetails 用户详细信息接口
  12. *
  13. * @param
  14. * @return
  15. * @throws Exception
  16. */
  17. @Data
  18. public class MyUserDetails implements UserDetails {
  19. private User user;
  20. private List<SimpleGrantedAuthority> simpleGrantedAuthorityList;
  21. public MyUserDetails(User user,List<SimpleGrantedAuthority> simpleGrantedAuthorityList){
  22. this.user=user;
  23. this.simpleGrantedAuthorityList=simpleGrantedAuthorityList;
  24. }
  25. /**
  26. * 获取所有权限
  27. * @return
  28. */
  29. @Override
  30. public Collection<? extends GrantedAuthority> getAuthorities() {
  31. return simpleGrantedAuthorityList;
  32. }
  33. @Override
  34. public String getPassword() {
  35. return user.getPassword();
  36. }
  37. @Override
  38. public String getUsername() {
  39. return user.getAccount();
  40. }
  41. @Override
  42. public boolean isAccountNonExpired() {
  43. return true;
  44. }
  45. @Override
  46. public boolean isAccountNonLocked() {
  47. return true;
  48. }
  49. @Override
  50. public boolean isCredentialsNonExpired() {
  51. return true;
  52. }
  53. //是否启用 true:启用, false:禁用
  54. @Override
  55. public boolean isEnabled() {
  56. return true;
  57. }
  58. /**
  59. * 二次处理权限
  60. * 获取字符串集合的权限
  61. * @return
  62. */
  63. public List<String>getAuthList(){
  64. //转成list集合
  65. return simpleGrantedAuthorityList.stream().map(x->x.getAuthority()).collect(Collectors.toList());
  66. }
  67. }
  1. package com.dmg.sp.entity;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableId;
  4. import com.baomidou.mybatisplus.annotation.TableName;
  5. import lombok.Data;
  6. @Data
  7. @TableName("sys_role")
  8. public class Role {
  9. @TableId(type = IdType.AUTO)
  10. private Integer id;
  11. //角色编码
  12. private String roleCode;
  13. //角色名称
  14. private String roleName;
  15. }
  1. package com.dmg.sp.entity;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import com.fasterxml.jackson.annotation.JsonFormat;
  7. import lombok.Data;
  8. import java.util.Date;
  9. import java.util.List;
  10. @Data
  11. @TableName("sys_user")
  12. public class User {
  13. @TableId(type = IdType.AUTO)
  14. private Integer id;
  15. //账号
  16. private String account;
  17. //密码
  18. private String password;
  19. //姓名
  20. private String name;
  21. //创建日期
  22. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
  23. private Date createTime;
  24. @TableField(exist = false)
  25. private List<Menu> menu;
  26. }

service

  1. package com.dmg.sp.service;
  2. import com.dmg.sp.utils.Result;
  3. import com.dmg.sp.vo.LoginVo;
  4. public interface LoginService {
  5. public Result login(LoginVo vo);
  6. }
  1. package com.dmg.sp.service;
  2. import com.dmg.sp.entity.Menu;
  3. import org.springframework.web.bind.annotation.RequestBody;
  4. import java.util.List;
  5. public interface MenuService {
  6. List<Menu> getMenuList();
  7. public void addMenu(Menu menu);
  8. public void editMenu(Menu menu);
  9. public void deleteMenu(Integer id);
  10. public Menu getMenuById(Integer id);
  11. public List<String> getRoleAuth(Integer roleId);
  12. /**
  13. * 获取当前登录人的菜单信息
  14. * @return
  15. */
  16. public List<Menu> getMyMenu();
  17. }
  1. package com.dmg.sp.service;
  2. import com.dmg.sp.entity.Role;
  3. import com.dmg.sp.utils.Result;
  4. import com.dmg.sp.vo.IdVo;
  5. import com.dmg.sp.vo.RoleAuthVo;
  6. import org.springframework.web.bind.annotation.PostMapping;
  7. import org.springframework.web.bind.annotation.RequestBody;
  8. import java.util.List;
  9. public interface RoleService {
  10. public List<Role>getRoleList();
  11. public void addRole(Role role);
  12. public void editRole(Role role);
  13. public void deleteRole(Integer id);
  14. public Role getRoleById(Integer id);
  15. public List<Role> getUserRole(Integer userId);
  16. public void setRoleAuth(RoleAuthVo vo);
  17. }
  1. package com.dmg.sp.service;
  2. import com.dmg.sp.entity.User;
  3. import com.dmg.sp.utils.Result;
  4. import com.dmg.sp.vo.UserRoleVo;
  5. import org.apache.ibatis.annotations.Param;
  6. import org.springframework.web.bind.annotation.PostMapping;
  7. import org.springframework.web.bind.annotation.RequestBody;
  8. import java.util.List;
  9. public interface SysUserService {
  10. List<User> getUserList();
  11. /**
  12. * 为用户分配角色
  13. * @return
  14. */
  15. public void setUserRole(UserRoleVo vo);
  16. public void addUser(User user);
  17. /**
  18. * 查看用户对应的角色id
  19. * @return
  20. */
  21. public List<Integer>getUserRoleIds(Integer userId);
  22. }
  1. package com.dmg.sp.service;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
  4. import com.dmg.sp.dao.MenuMapper;
  5. import com.dmg.sp.dao.UserMapper;
  6. import com.dmg.sp.entity.Menu;
  7. import com.dmg.sp.entity.MyUserDetails;
  8. import com.dmg.sp.entity.User;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  12. import org.springframework.security.core.userdetails.UserDetails;
  13. import org.springframework.security.core.userdetails.UserDetailsService;
  14. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  15. import org.springframework.stereotype.Service;
  16. import java.util.ArrayList;
  17. import java.util.Collections;
  18. import java.util.List;
  19. /**
  20. * UserDetailsService 用户查询接口
  21. *
  22. * @param
  23. * @return
  24. * @throws Exception
  25. */
  26. @Slf4j
  27. @Service
  28. public class UserService implements UserDetailsService {
  29. @Autowired
  30. private UserMapper userMapper;
  31. @Autowired
  32. private MenuMapper menuMapper;
  33. /**
  34. * 根据账号查询用户信息
  35. * @param
  36. * @return
  37. * @throws Exception
  38. */
  39. @Override
  40. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  41. log.info("根据账号查询用户信息==========================================================");
  42. QueryWrapper<User>queryWrapper=new QueryWrapper<>();
  43. queryWrapper.eq("account",username);
  44. User user = userMapper.selectOne(queryWrapper);
  45. if(user==null){
  46. log.info("用户不存在");
  47. throw new UsernameNotFoundException("用户不存在");
  48. }
  49. //根据用户id获取权限信息
  50. List<Menu>auths=getAuthList(user.getId());
  51. //组装权限信息 放入 SimpleGrantedAuthority
  52. List<SimpleGrantedAuthority> simpleGrantedAuthorityList=getGrantedAuthority(auths);
  53. //把权限放入用户对象中
  54. user.setMenu(auths);
  55. //最后返回UserDetails对象
  56. return new MyUserDetails(user,simpleGrantedAuthorityList);
  57. }
  58. /**
  59. * 组装权限信息 放入 SimpleGrantedAuthority
  60. * @return
  61. */
  62. private List<SimpleGrantedAuthority> getGrantedAuthority(List<Menu>auths){
  63. List<SimpleGrantedAuthority> list=new ArrayList<>();
  64. for (Menu x : auths) {
  65. SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(x.getAuth());
  66. list.add(simpleGrantedAuthority);
  67. }
  68. return list;
  69. }
  70. /**
  71. * 根据用户id 获取所有权限
  72. * 在分配权限的时候 如果只选择了按钮
  73. * 那么也会把他的父级菜单给查询出来
  74. *
  75. * 只有按钮都不选择的时候 菜单才不展示
  76. * @param userId
  77. * @return
  78. */
  79. private List<Menu> getAuthList(Integer userId){
  80. //查询用户关联的菜单id 按钮
  81. List<Integer> menuIds = menuMapper.getMenuIdsByUserId(userId);
  82. if(CollectionUtils.isEmpty(menuIds)){
  83. //如果还没有授权 直接返回空
  84. return new ArrayList<>();
  85. }
  86. //根据菜单id 查询父级 id 二级菜单
  87. List<Integer> pIds=menuMapper.getPIdsByIds(menuIds);
  88. if(CollectionUtils.isEmpty(pIds)){
  89. //如果没有父级id 直接返回关联的权限
  90. return menuMapper.getAuthList(menuIds);
  91. }
  92. //根据pIds 查询父级 id 一级菜单
  93. List<Integer> oneIds=menuMapper.getPIdsByIds(pIds);
  94. //通过所有的菜单id 查询权限信息
  95. oneIds.addAll(pIds);
  96. oneIds.addAll(menuIds);
  97. return menuMapper.getAuthList(oneIds);
  98. }
  99. }

impl

  1. package com.dmg.sp.service.impl;
  2. import com.dmg.sp.entity.MyUserDetails;
  3. import com.dmg.sp.service.LoginService;
  4. import com.dmg.sp.utils.JWTUtil;
  5. import com.dmg.sp.utils.Result;
  6. import com.dmg.sp.vo.LoginVo;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.security.authentication.AuthenticationManager;
  10. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  11. import org.springframework.security.core.Authentication;
  12. import org.springframework.stereotype.Service;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. import java.util.Objects;
  16. @Slf4j
  17. @Service
  18. public class LoginServiceImpl implements LoginService {
  19. //认证管理器
  20. @Autowired
  21. private AuthenticationManager authenticationManager;
  22. @Override
  23. public Result login(LoginVo vo) {
  24. //根据账号和密码 创建 认证令牌对象
  25. UsernamePasswordAuthenticationToken upt=new UsernamePasswordAuthenticationToken(vo.getAccount(),vo.getPassword());
  26. //进行登录 获取认证信息
  27. Authentication authenticate = authenticationManager.authenticate(upt);
  28. if(authenticate==null){
  29. throw new RuntimeException("登录失败");
  30. }
  31. Map<String,String> map=new HashMap<>();
  32. map.put("account",vo.getAccount());
  33. //第二个参数是盐值
  34. //获取token
  35. String token= JWTUtil.getToken(map,"123456789");
  36. return Result.success(token);
  37. }
  38. }
  1. package com.dmg.sp.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.dmg.sp.dao.MenuMapper;
  4. import com.dmg.sp.entity.Menu;
  5. import com.dmg.sp.entity.MyUserDetails;
  6. import com.dmg.sp.entity.Role;
  7. import com.dmg.sp.service.MenuService;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.security.core.Authentication;
  11. import org.springframework.security.core.context.SecurityContextHolder;
  12. import org.springframework.stereotype.Service;
  13. import org.springframework.transaction.annotation.Transactional;
  14. import org.springframework.util.CollectionUtils;
  15. import org.springframework.util.StringUtils;
  16. import java.util.ArrayList;
  17. import java.util.Date;
  18. import java.util.List;
  19. @Slf4j
  20. @Service
  21. public class MenuServiceImpl implements MenuService {
  22. @Autowired
  23. private MenuMapper menuMapper;
  24. /**
  25. * 获取所有菜单
  26. * @return
  27. */
  28. @Override
  29. public List<Menu> getMenuList() {
  30. List<Menu>res=new ArrayList<>();
  31. List<Menu>list=menuMapper.getMenuList();
  32. //递归放入 子菜单
  33. for (Menu x : list) {
  34. if(x.getIsType().equals("2")){
  35. //如果是按钮 直接跳过 因为是 最后一层
  36. continue;
  37. }
  38. dfs(x,list);
  39. if(x.getParentId()==0){
  40. //只把一级菜单放入集合中 其他级别的菜单都在一级菜单的子集中
  41. res.add(x);
  42. }
  43. }
  44. return res;
  45. }
  46. /**
  47. * 添加菜单
  48. * @param menu
  49. */
  50. @Transactional(rollbackFor = Exception.class)
  51. @Override
  52. public void addMenu(Menu menu) {
  53. //根据权限查询是否存在
  54. if(getByAuth(menu.getAuth())!=null){
  55. throw new RuntimeException("权限已存在");
  56. }
  57. menu.setCreateTime(new Date());
  58. menuMapper.insert(menu);
  59. }
  60. /**
  61. * 修改菜单
  62. * @param menu
  63. */
  64. @Transactional(rollbackFor = Exception.class)
  65. @Override
  66. public void editMenu(Menu menu) {
  67. Menu bean=menuMapper.selectById(menu.getId());
  68. if(bean==null){
  69. throw new RuntimeException("菜单不存在");
  70. }
  71. Menu item=getByAuth(menu.getAuth());
  72. if(item!=null && !item.getAuth().equals(bean.getAuth())){
  73. //如果不是当前菜单的权限,并且已存在 那么抛出异常
  74. throw new RuntimeException("权限已存在");
  75. }
  76. menuMapper.updateById(menu);
  77. }
  78. /**
  79. * 删除菜单
  80. * @param id
  81. */
  82. @Transactional(rollbackFor = Exception.class)
  83. @Override
  84. public void deleteMenu(Integer id) {
  85. //判断菜单是否存在
  86. if(menuMapper.selectById(id)==null){
  87. throw new RuntimeException("菜单不存在");
  88. }
  89. //判断当前是否有子集,如果有子集 不允许删除
  90. if(getPIdCount(id)>0){
  91. throw new RuntimeException("当前菜单下,还有子集,请先删除子集");
  92. }
  93. //删除菜单关联的角色
  94. menuMapper.deleteRole(id);
  95. //删除菜单
  96. menuMapper.deleteById(id);
  97. }
  98. /**
  99. * 根据菜单id 查看详情
  100. * @param id
  101. */
  102. @Override
  103. public Menu getMenuById(Integer id) {
  104. return menuMapper.selectById(id);
  105. }
  106. /**
  107. * 查看角色对应的权限
  108. * @return
  109. */
  110. @Override
  111. public List<String> getRoleAuth(Integer roleId) {
  112. return menuMapper.getRoleAuth(roleId);
  113. }
  114. /**
  115. * 递归放入父级中
  116. * @param x
  117. * @param list
  118. */
  119. private void dfs(Menu x,List<Menu>list){
  120. for (Menu menu : list) {
  121. if(menu.getParentId().equals(x.getId())){
  122. //如果子集 匹配上了父级 那么把子集放入父级中
  123. List<Menu> children = x.getChildren();
  124. if(CollectionUtils.isEmpty(children)){
  125. children=new ArrayList<>();
  126. }
  127. children.add(menu);
  128. x.setChildren(children);
  129. }
  130. }
  131. }
  132. /**
  133. * 根据权限获取菜单信息
  134. * @return
  135. */
  136. private Menu getByAuth(String auth){
  137. QueryWrapper<Menu> queryWrapper=new QueryWrapper();
  138. queryWrapper.eq("auth",auth);
  139. Menu x=menuMapper.selectOne(queryWrapper);
  140. return x;
  141. }
  142. /**
  143. * 获取是否有子集
  144. * @return
  145. */
  146. private Long getPIdCount(Integer parentId){
  147. QueryWrapper<Menu> queryWrapper=new QueryWrapper();
  148. queryWrapper.eq("parent_id",parentId);
  149. return menuMapper.selectCount(queryWrapper);
  150. }
  151. /**
  152. * 获取当前登录人的菜单信息
  153. * @return
  154. */
  155. @Override
  156. public List<Menu> getMyMenu() {
  157. //从认证信息上下文中 获取用户权限
  158. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  159. if(authentication.getPrincipal() instanceof MyUserDetails){
  160. MyUserDetails myUserDetails =(MyUserDetails) authentication.getPrincipal();
  161. return myUserDetails.getUser().getMenu();
  162. }
  163. return new ArrayList<>();
  164. }
  165. }
  1. package com.dmg.sp.service.impl;
  2. import com.dmg.sp.service.UserService;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.security.authentication.AuthenticationProvider;
  7. import org.springframework.security.authentication.BadCredentialsException;
  8. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  9. import org.springframework.security.core.Authentication;
  10. import org.springframework.security.core.AuthenticationException;
  11. import org.springframework.security.core.userdetails.UserDetails;
  12. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  13. import org.springframework.security.crypto.password.PasswordEncoder;
  14. import org.springframework.stereotype.Component;
  15. /**
  16. *
  17. * 实现身份验证提供程序
  18. * @param
  19. * @return
  20. * @throws Exception
  21. */
  22. @Slf4j
  23. @Component
  24. public class MyAuthenticationProvider implements AuthenticationProvider {
  25. @Autowired
  26. private UserService userService;
  27. @Autowired
  28. private PasswordEncoder passwordEncoder;
  29. /**
  30. * LoginServiceImpl的登录方法点击认证的时候 直接跳转到这里
  31. * 登陆认证
  32. * @param
  33. * @return
  34. * @throws Exception
  35. */
  36. @Override
  37. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  38. //从authentication获取用户名和凭证(密码)信息
  39. String username=authentication.getName();
  40. String password=authentication.getCredentials().toString();
  41. log.info("密码=========================={}",password);
  42. //查询用户是否存在
  43. UserDetails userDetails = userService.loadUserByUsername(username);
  44. //比较和数据库的密码是否一样
  45. if(passwordEncoder.matches(password,userDetails.getPassword())){
  46. //返回用户名密码认证令牌
  47. //因为UsernamePasswordAuthenticationToken的上级父类的父类是Authentication 所以可以直接返回
  48. return new UsernamePasswordAuthenticationToken(username,password,userDetails.getAuthorities());
  49. }else {
  50. throw new BadCredentialsException("用户名或者密码错误了");
  51. }
  52. }
  53. @Override
  54. public boolean supports(Class<?> authentication) {
  55. //保证认证和返回的对象都是UsernamePasswordAuthenticationToken
  56. return authentication.equals(UsernamePasswordAuthenticationToken.class);
  57. }
  58. }
  1. package com.dmg.sp.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
  4. import com.dmg.sp.dao.RoleMapper;
  5. import com.dmg.sp.entity.Role;
  6. import com.dmg.sp.service.RoleService;
  7. import com.dmg.sp.vo.RoleAuthVo;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Service;
  11. import org.springframework.transaction.annotation.Transactional;
  12. import java.util.List;
  13. @Slf4j
  14. @Service
  15. public class RoleServiceImpl implements RoleService {
  16. @Autowired
  17. private RoleMapper roleMapper;
  18. /**
  19. * 获取所有角色
  20. * @return
  21. */
  22. @Override
  23. public List<Role> getRoleList() {
  24. return roleMapper.selectList(null);
  25. }
  26. /**
  27. * 添加角色
  28. * @param role
  29. */
  30. @Transactional(rollbackFor = Exception.class)
  31. @Override
  32. public void addRole(Role role) {
  33. //根据角色编码查询是否存在相同的角色
  34. if(getRoleByCode(role.getRoleCode())!=null){
  35. throw new RuntimeException("角色编码已存在");
  36. }
  37. roleMapper.insert(role);
  38. }
  39. /**
  40. * 修改角色
  41. * @param role
  42. */
  43. @Transactional(rollbackFor = Exception.class)
  44. @Override
  45. public void editRole(Role role) {
  46. Role bean=roleMapper.selectById(role.getId());
  47. if(bean==null){
  48. throw new RuntimeException("角色不存在");
  49. }
  50. Role item=getRoleByCode(role.getRoleCode());
  51. if(item!=null && !item.getRoleCode().equals(bean.getRoleCode())){
  52. //如果要修改的角色已存在,但是 不是当前角色的编码 那么抛出异常
  53. throw new RuntimeException("角色编码已存在");
  54. }
  55. roleMapper.updateById(role);
  56. }
  57. /**
  58. * 删除角色
  59. * @param id
  60. */
  61. @Transactional(rollbackFor = Exception.class)
  62. @Override
  63. public void deleteRole(Integer id) {
  64. //判断角色是否存在
  65. Role role=roleMapper.selectById(id);
  66. if(role==null){
  67. throw new RuntimeException("角色不存在");
  68. }
  69. if(role.getRoleCode().equals("admin")){
  70. throw new RuntimeException("管理员不能删除");
  71. }
  72. //删除角色关联的用户
  73. roleMapper.deleteUser(id);
  74. //删除角色关联的权限
  75. roleMapper.deleteAuth(id);
  76. //删除角色
  77. roleMapper.deleteById(id);
  78. }
  79. /**
  80. * 根据角色id 查看角色详情
  81. * @param id
  82. * @return
  83. */
  84. @Override
  85. public Role getRoleById(Integer id) {
  86. return roleMapper.selectById(id);
  87. }
  88. /**
  89. * 查看用户对应的角色
  90. * @param userId
  91. * @return
  92. */
  93. @Override
  94. public List<Role> getUserRole(Integer userId) {
  95. return roleMapper.getUserRole(userId);
  96. }
  97. /**
  98. * 为角色分配权限
  99. * @return
  100. */
  101. @Override
  102. public void setRoleAuth(RoleAuthVo vo) {
  103. //判断角色是否存在
  104. if(roleMapper.selectById(vo.getRoleId())==null){
  105. throw new RuntimeException("角色不存在");
  106. }
  107. if(CollectionUtils.isEmpty(vo.getMenuIds())){
  108. throw new RuntimeException("权限不能为空");
  109. }
  110. //先删除旧的角色权限
  111. roleMapper.deleteAuth(vo.getRoleId());
  112. //在添加新的角色权限
  113. roleMapper.addRoleAuth(vo.getRoleId(),vo.getMenuIds());
  114. }
  115. /**
  116. * 根据角色编码获取角色信息
  117. * @param code
  118. * @return
  119. */
  120. private Role getRoleByCode(String code){
  121. QueryWrapper<Role> queryWrapper=new QueryWrapper();
  122. queryWrapper.eq("role_code",code);
  123. Role role=roleMapper.selectOne(queryWrapper);
  124. return role;
  125. }
  126. }
  1. package com.dmg.sp.service.impl;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
  4. import com.dmg.sp.dao.UserMapper;
  5. import com.dmg.sp.entity.Role;
  6. import com.dmg.sp.entity.User;
  7. import com.dmg.sp.service.SysUserService;
  8. import com.dmg.sp.vo.UserRoleVo;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  12. import org.springframework.stereotype.Service;
  13. import org.springframework.transaction.annotation.Transactional;
  14. import java.util.Date;
  15. import java.util.List;
  16. @Slf4j
  17. @Service
  18. public class SysUserServiceImpl implements SysUserService {
  19. @Autowired
  20. private UserMapper userMapper;
  21. /**
  22. * 获取所有用户
  23. * @return
  24. */
  25. @Override
  26. public List<User> getUserList() {
  27. return userMapper.selectList(null);
  28. }
  29. /**
  30. * 为用户分配角色
  31. * @return
  32. */
  33. @Transactional(rollbackFor = Exception.class)
  34. @Override
  35. public void setUserRole(UserRoleVo vo) {
  36. //判断用户是否存在
  37. if(vo.getUserId()==null || userMapper.selectById(vo.getUserId())==null){
  38. throw new RuntimeException("用户不存在");
  39. }
  40. if(CollectionUtils.isEmpty(vo.getRoleIds())){
  41. throw new RuntimeException("角色不能为空");
  42. }
  43. //先删除旧的用户角色
  44. userMapper.deleteRole(vo.getUserId());
  45. //在添加新的用户角色
  46. userMapper.addUserRole(vo.getUserId(),vo.getRoleIds());
  47. }
  48. /**
  49. * 添加用户
  50. * @param user
  51. */
  52. @Transactional(rollbackFor = Exception.class)
  53. @Override
  54. public void addUser(User user) {
  55. //根据账号获取用户信息
  56. if(getByAccount(user.getAccount())!=null){
  57. throw new RuntimeException("该账号已存在");
  58. }
  59. //对密码进行加密
  60. BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
  61. String encode = bCryptPasswordEncoder.encode(user.getPassword());
  62. user.setPassword(encode);
  63. user.setCreateTime(new Date());
  64. userMapper.insert(user);
  65. }
  66. /**
  67. * 查看用户对应的角色id
  68. * @return
  69. */
  70. @Override
  71. public List<Integer> getUserRoleIds(Integer userId) {
  72. return userMapper.getUserRoleIds(userId);
  73. }
  74. /**
  75. * 根据账号获取用户信息
  76. * @param account
  77. * @return
  78. */
  79. private User getByAccount(String account){
  80. QueryWrapper<User> queryWrapper=new QueryWrapper();
  81. queryWrapper.eq("account",account);
  82. User x=userMapper.selectOne(queryWrapper);
  83. return x;
  84. }
  85. }

utils

  1. package com.dmg.sp.utils;
  2. import com.auth0.jwt.JWT;
  3. import com.auth0.jwt.JWTCreator;
  4. import com.auth0.jwt.algorithms.Algorithm;
  5. import com.auth0.jwt.interfaces.Claim;
  6. import com.auth0.jwt.interfaces.DecodedJWT;
  7. import java.util.Calendar;
  8. import java.util.Map;
  9. public class JWTUtil {
  10. /**
  11. * 传入payload信息获取token
  12. */
  13. public static String getToken(Map<String, String> map, String secret) {
  14. JWTCreator.Builder builder = JWT.create();
  15. //payload
  16. map.forEach(builder::withClaim);
  17. Calendar instance = Calendar.getInstance();
  18. //默认7天过期
  19. instance.add(Calendar.DATE, 7);
  20. //指定令牌的过期时间
  21. builder.withExpiresAt(instance.getTime());
  22. return builder.sign(Algorithm.HMAC256(secret));
  23. }
  24. /**
  25. * 验证token 合法性
  26. */
  27. public static DecodedJWT verify(String token, String secret) {
  28. //如果有任何验证异常,此处都会抛出异常
  29. return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
  30. }
  31. /**
  32. * 获取token信息方法
  33. */
  34. public static Map<String, Claim> getTokenInfo(String token, String secret) {
  35. return JWT.require(Algorithm.HMAC256(secret)).build().verify(token).getClaims();
  36. }
  37. }
  1. package com.dmg.sp.utils;
  2. import jakarta.servlet.http.HttpServletRequest;
  3. import jakarta.servlet.http.HttpServletResponse;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.security.authentication.BadCredentialsException;
  7. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  8. import org.springframework.web.bind.annotation.ExceptionHandler;
  9. import org.springframework.web.bind.annotation.RestControllerAdvice;
  10. import java.net.BindException;
  11. /**
  12. * 全局异常处理器
  13. */
  14. @Slf4j
  15. @RestControllerAdvice
  16. public class MyGlobalExceptionHandler {
  17. @ExceptionHandler(UsernameNotFoundException.class)
  18. public Result usernameNotFoundException(UsernameNotFoundException e) {
  19. return Result.error("401",e.getMessage());
  20. }
  21. @ExceptionHandler(BadCredentialsException.class)
  22. public Result badCredentialsException(BadCredentialsException e) {
  23. return Result.error("401",e.getMessage());
  24. }
  25. @ExceptionHandler(Exception.class)
  26. public Result exception(Exception e) {
  27. return Result.error("500",e.getMessage());
  28. }
  29. }
  1. package com.dmg.sp.utils;
  2. import lombok.Data;
  3. /**
  4. * 返回对象
  5. * @param <T>
  6. */
  7. @Data
  8. public class Result<T> {
  9. private String code;
  10. private String msg;
  11. private T data;
  12. private static String SUCCESS="200";
  13. private static String ERROR="500";
  14. //禁止外部new对象
  15. private Result(){
  16. }
  17. public static <T> Result<T> success(String code,String msg,T data){
  18. Result result=new Result();
  19. result.setCode(code);
  20. result.setMsg(msg);
  21. result.setData(data);
  22. return result;
  23. }
  24. public static <T> Result<T> success(String msg,T data){
  25. Result result=new Result();
  26. result.setCode(SUCCESS);
  27. result.setMsg(msg);
  28. result.setData(data);
  29. return result;
  30. }
  31. public static <T> Result<T> success(T data){
  32. Result result=new Result();
  33. result.setCode(SUCCESS);
  34. result.setMsg(null);
  35. result.setData(data);
  36. return result;
  37. }
  38. public static <T> Result<T> success(){
  39. Result result=new Result();
  40. result.setCode(SUCCESS);
  41. result.setMsg(null);
  42. result.setData(null);
  43. return result;
  44. }
  45. public static <T> Result<T> error(String code,String msg){
  46. Result result=new Result();
  47. result.setCode(code);
  48. result.setMsg(msg);
  49. result.setData(null);
  50. return result;
  51. }
  52. public static <T> Result<T> error(String msg){
  53. Result result=new Result();
  54. result.setCode(ERROR);
  55. result.setMsg(msg);
  56. result.setData(null);
  57. return result;
  58. }
  59. public static <T> Result<T> error(){
  60. Result result=new Result();
  61. result.setCode(ERROR);
  62. result.setMsg(null);
  63. result.setData(null);
  64. return result;
  65. }
  66. }

vo

  1. package com.dmg.sp.vo;
  2. import lombok.Data;
  3. @Data
  4. public class IdVo {
  5. //用户id
  6. private Integer userId;
  7. //角色id
  8. private Integer roleId;
  9. //菜单id
  10. private Integer menuId;
  11. }
  1. package com.dmg.sp.vo;
  2. import lombok.Data;
  3. @Data
  4. public class LoginVo {
  5. //账号
  6. private String account;
  7. //密码
  8. private String password;
  9. }
  1. package com.dmg.sp.vo;
  2. import lombok.Data;
  3. import java.util.List;
  4. @Data
  5. public class RoleAuthVo {
  6. //角色id
  7. private Integer roleId;
  8. //菜单id 集合
  9. private List<Integer> menuIds;
  10. }
  1. package com.dmg.sp.vo;
  2. import lombok.Data;
  3. import java.util.List;
  4. @Data
  5. public class UserRoleVo {
  6. //用户id
  7. private Integer userId;
  8. //角色id 集合
  9. private List<Integer> roleIds;
  10. }

启动类

  1. package com.dmg.sp;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.mybatis.spring.annotation.MapperScans;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. import org.springframework.context.annotation.ComponentScan;
  7. @MapperScan(basePackages = {"com.dmg.sp.dao"})
  8. @SpringBootApplication
  9. public class SpApplication {
  10. public static void main(String[] args) {
  11. SpringApplication.run(SpApplication.class, args);
  12. }
  13. }

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号