From 6413e5fd87bcec030c90136de03b95060e11634a Mon Sep 17 00:00:00 2001
From: Jie Zheng <201507802@qq.com>
Date: Tue, 14 Jan 2025 14:58:53 +0800
Subject: [PATCH] =?UTF-8?q?refactor:=20SecurityUtils=E4=BC=98=E5=8C=96?=
=?UTF-8?q?=E8=8E=B7=E5=8F=96=E7=94=A8=E6=88=B7=E5=90=8D=E4=B8=8E=E7=94=A8?=
=?UTF-8?q?=E6=88=B7ID=E6=96=B9=E5=BC=8F?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
eladmin-web/src/views/tools/swagger/index.vue | 16 ---
.../java/me/zhengjie/utils/SecurityUtils.java | 108 ++++++++++++------
.../security/config/SpringSecurityConfig.java | 4 +-
.../modules/security/rest/AuthController.java | 2 +-
.../security/security/TokenConfigurer.java | 4 +-
.../security/security/TokenFilter.java | 37 ++----
.../security/security/TokenProvider.java | 32 +++---
sql/eladmin.sql | 2 -
8 files changed, 107 insertions(+), 98 deletions(-)
delete mode 100644 eladmin-web/src/views/tools/swagger/index.vue
diff --git a/eladmin-web/src/views/tools/swagger/index.vue b/eladmin-web/src/views/tools/swagger/index.vue
deleted file mode 100644
index 5162cd9..0000000
--- a/eladmin-web/src/views/tools/swagger/index.vue
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
-
diff --git a/eladmin/eladmin-common/src/main/java/me/zhengjie/utils/SecurityUtils.java b/eladmin/eladmin-common/src/main/java/me/zhengjie/utils/SecurityUtils.java
index da24b42..c24180e 100644
--- a/eladmin/eladmin-common/src/main/java/me/zhengjie/utils/SecurityUtils.java
+++ b/eladmin/eladmin-common/src/main/java/me/zhengjie/utils/SecurityUtils.java
@@ -16,18 +16,22 @@
package me.zhengjie.utils;
import cn.hutool.core.collection.CollUtil;
+import cn.hutool.jwt.JWT;
+import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
-import me.zhengjie.exception.BadRequestException;
import me.zhengjie.utils.enums.DataScopeEnum;
-import org.springframework.http.HttpStatus;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import javax.servlet.http.HttpServletRequest;
import java.util.List;
+import java.util.Objects;
/**
* 获取当前登录的用户
@@ -35,8 +39,23 @@ import java.util.List;
* @date 2019-01-17
*/
@Slf4j
+@Component
public class SecurityUtils {
+ public static String header;
+
+ public static String tokenStartWith;
+
+ @Value("${jwt.header}")
+ public void setHeader(String header) {
+ SecurityUtils.header = header;
+ }
+
+ @Value("${jwt.token-start-with}")
+ public void setTokenStartWith(String tokenStartWith) {
+ SecurityUtils.tokenStartWith = tokenStartWith;
+ }
+
/**
* 获取当前登录的用户
* @return UserDetails
@@ -46,34 +65,6 @@ public class SecurityUtils {
return userDetailsService.loadUserByUsername(getCurrentUsername());
}
- /**
- * 获取系统用户名称
- *
- * @return 系统用户名称
- */
- public static String getCurrentUsername() {
- final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- if (authentication == null) {
- throw new BadRequestException(HttpStatus.UNAUTHORIZED, "当前登录状态过期");
- }
- if (authentication.getPrincipal() instanceof UserDetails) {
- UserDetails userDetails = (UserDetails) authentication.getPrincipal();
- return userDetails.getUsername();
- }
- throw new BadRequestException(HttpStatus.UNAUTHORIZED, "找不到当前登录的信息");
- }
-
- /**
- * 获取系统用户ID
- * @return 系统用户ID
- */
- public static Long getCurrentUserId() {
- UserDetails userDetails = getCurrentUser();
- // 将 Java 对象转换为 JSONObject 对象
- JSONObject jsonObject = (JSONObject) JSON.toJSON(userDetails);
- return jsonObject.getJSONObject("user").getLong("id");
- }
-
/**
* 获取当前用户的数据权限
* @return /
@@ -97,4 +88,57 @@ public class SecurityUtils {
}
return DataScopeEnum.ALL.getValue();
}
+
+ /**
+ * 获取用户ID
+ * @return 系统用户ID
+ */
+ public static Long getCurrentUserId() {
+ return getCurrentUserId(getToken());
+ }
+
+ /**
+ * 获取用户ID
+ * @return 系统用户ID
+ */
+ public static Long getCurrentUserId(String token) {
+ JWT jwt = JWTUtil.parseToken(token);
+ return Long.valueOf(jwt.getPayload("userId").toString());
+ }
+
+ /**
+ * 获取系统用户名称
+ *
+ * @return 系统用户名称
+ */
+ public static String getCurrentUsername() {
+ return getCurrentUsername(getToken());
+ }
+
+ /**
+ * 获取系统用户名称
+ *
+ * @return 系统用户名称
+ */
+ public static String getCurrentUsername(String token) {
+ JWT jwt = JWTUtil.parseToken(token);
+ return jwt.getPayload("sub").toString();
+ }
+
+ /**
+ * 获取Token
+ * @return /
+ */
+ public static String getToken() {
+ HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder
+ .getRequestAttributes())).getRequest();
+ String bearerToken = request.getHeader(header);
+ if (bearerToken != null && bearerToken.startsWith(tokenStartWith)) {
+ // 去掉令牌前缀
+ return bearerToken.replace(tokenStartWith, "");
+ } else {
+ log.debug("非法Token:{}", bearerToken);
+ }
+ return null;
+ }
}
diff --git a/eladmin/eladmin-system/src/main/java/me/zhengjie/modules/security/config/SpringSecurityConfig.java b/eladmin/eladmin-system/src/main/java/me/zhengjie/modules/security/config/SpringSecurityConfig.java
index 711d7dd..9fac2ea 100644
--- a/eladmin/eladmin-system/src/main/java/me/zhengjie/modules/security/config/SpringSecurityConfig.java
+++ b/eladmin/eladmin-system/src/main/java/me/zhengjie/modules/security/config/SpringSecurityConfig.java
@@ -18,7 +18,6 @@ package me.zhengjie.modules.security.config;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.security.security.*;
import me.zhengjie.modules.security.service.OnlineUserService;
-import me.zhengjie.modules.security.service.UserCacheManager;
import me.zhengjie.utils.AnonTagUtils;
import me.zhengjie.utils.enums.RequestMethodEnum;
import org.springframework.context.ApplicationContext;
@@ -52,7 +51,6 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
private final ApplicationContext applicationContext;
private final SecurityProperties properties;
private final OnlineUserService onlineUserService;
- private final UserCacheManager userCacheManager;
@Bean
GrantedAuthorityDefaults grantedAuthorityDefaults() {
@@ -129,6 +127,6 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
}
private TokenConfigurer securityConfigurerAdapter() {
- return new TokenConfigurer(tokenProvider, properties, onlineUserService, userCacheManager);
+ return new TokenConfigurer(tokenProvider, properties, onlineUserService);
}
}
diff --git a/eladmin/eladmin-system/src/main/java/me/zhengjie/modules/security/rest/AuthController.java b/eladmin/eladmin-system/src/main/java/me/zhengjie/modules/security/rest/AuthController.java
index 6c8b0e3..10b4f47 100644
--- a/eladmin/eladmin-system/src/main/java/me/zhengjie/modules/security/rest/AuthController.java
+++ b/eladmin/eladmin-system/src/main/java/me/zhengjie/modules/security/rest/AuthController.java
@@ -100,7 +100,7 @@ public class AuthController {
Authentication authentication = new UsernamePasswordAuthenticationToken(jwtUser, null, jwtUser.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
// 生成令牌
- String token = tokenProvider.createToken(authentication);
+ String token = tokenProvider.createToken(jwtUser);
// 将密码设置为空
jwtUser.setPassword(null);
// 返回 token 与 用户信息
diff --git a/eladmin/eladmin-system/src/main/java/me/zhengjie/modules/security/security/TokenConfigurer.java b/eladmin/eladmin-system/src/main/java/me/zhengjie/modules/security/security/TokenConfigurer.java
index 208e4ab..6338faa 100644
--- a/eladmin/eladmin-system/src/main/java/me/zhengjie/modules/security/security/TokenConfigurer.java
+++ b/eladmin/eladmin-system/src/main/java/me/zhengjie/modules/security/security/TokenConfigurer.java
@@ -18,7 +18,6 @@ package me.zhengjie.modules.security.security;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.security.config.SecurityProperties;
import me.zhengjie.modules.security.service.OnlineUserService;
-import me.zhengjie.modules.security.service.UserCacheManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
@@ -33,11 +32,10 @@ public class TokenConfigurer extends SecurityConfigurerAdapter claims = new HashMap<>(6);
+ // 设置用户ID
+ claims.put(AUTHORITIES_UID_KEY, user.getUser().getId());
+ // 设置UUID,确保每次Token不一样
+ claims.put(AUTHORITIES_UUID_KEY, IdUtil.simpleUUID());
return jwtBuilder
- // 加入ID确保生成的 Token 都不一致
- .setId(IdUtil.simpleUUID())
- .claim(AUTHORITIES_KEY, authentication.getName())
- .setSubject(authentication.getName())
+ .setClaims(claims)
+ .setSubject(user.getUsername())
.compact();
}
diff --git a/sql/eladmin.sql b/sql/eladmin.sql
index 91755a9..be7591d 100644
--- a/sql/eladmin.sql
+++ b/sql/eladmin.sql
@@ -273,7 +273,6 @@ INSERT INTO `sys_menu` (`menu_id`, `pid`, `sub_count`, `type`, `title`, `name`,
INSERT INTO `sys_menu` (`menu_id`, `pid`, `sub_count`, `type`, `title`, `name`, `component`, `menu_sort`, `icon`, `path`, `i_frame`, `cache`, `hidden`, `permission`, `create_by`, `update_by`, `create_time`, `update_time`) VALUES (35, 1, 3, 1, '部门管理', 'Dept', 'system/dept/index', 6, 'dept', 'dept', b'0', b'0', b'0', 'dept:list', NULL, NULL, '2019-03-25 09:46:00', NULL);
INSERT INTO `sys_menu` (`menu_id`, `pid`, `sub_count`, `type`, `title`, `name`, `component`, `menu_sort`, `icon`, `path`, `i_frame`, `cache`, `hidden`, `permission`, `create_by`, `update_by`, `create_time`, `update_time`) VALUES (36, NULL, 7, 0, '系统工具', NULL, '', 30, 'sys-tools', 'sys-tools', b'0', b'0', b'0', NULL, NULL, NULL, '2019-03-29 10:57:35', NULL);
INSERT INTO `sys_menu` (`menu_id`, `pid`, `sub_count`, `type`, `title`, `name`, `component`, `menu_sort`, `icon`, `path`, `i_frame`, `cache`, `hidden`, `permission`, `create_by`, `update_by`, `create_time`, `update_time`) VALUES (37, 1, 3, 1, '岗位管理', 'Job', 'system/job/index', 7, 'Steve-Jobs', 'job', b'0', b'0', b'0', 'job:list', NULL, NULL, '2019-03-29 13:51:18', NULL);
-INSERT INTO `sys_menu` (`menu_id`, `pid`, `sub_count`, `type`, `title`, `name`, `component`, `menu_sort`, `icon`, `path`, `i_frame`, `cache`, `hidden`, `permission`, `create_by`, `update_by`, `create_time`, `update_time`) VALUES (38, 36, 0, 1, '接口文档', 'Swagger', 'tools/swagger/index', 36, 'swagger', 'swagger2', b'0', b'0', b'0', NULL, NULL, NULL, '2019-03-29 19:57:53', NULL);
INSERT INTO `sys_menu` (`menu_id`, `pid`, `sub_count`, `type`, `title`, `name`, `component`, `menu_sort`, `icon`, `path`, `i_frame`, `cache`, `hidden`, `permission`, `create_by`, `update_by`, `create_time`, `update_time`) VALUES (39, 1, 3, 1, '字典管理', 'Dict', 'system/dict/index', 8, 'dictionary', 'dict', b'0', b'0', b'0', 'dict:list', NULL, NULL, '2019-04-10 11:49:04', NULL);
INSERT INTO `sys_menu` (`menu_id`, `pid`, `sub_count`, `type`, `title`, `name`, `component`, `menu_sort`, `icon`, `path`, `i_frame`, `cache`, `hidden`, `permission`, `create_by`, `update_by`, `create_time`, `update_time`) VALUES (41, 6, 0, 1, '在线用户', 'OnlineUser', 'monitor/online/index', 10, 'Steve-Jobs', 'online', b'0', b'0', b'0', NULL, NULL, NULL, '2019-10-26 22:08:43', NULL);
INSERT INTO `sys_menu` (`menu_id`, `pid`, `sub_count`, `type`, `title`, `name`, `component`, `menu_sort`, `icon`, `path`, `i_frame`, `cache`, `hidden`, `permission`, `create_by`, `update_by`, `create_time`, `update_time`) VALUES (44, 2, 0, 2, '用户新增', NULL, '', 2, '', '', b'0', b'0', b'0', 'user:add', NULL, NULL, '2019-10-29 10:59:46', NULL);
@@ -472,7 +471,6 @@ INSERT INTO `sys_roles_menus` (`menu_id`, `role_id`) VALUES (35, 1);
INSERT INTO `sys_roles_menus` (`menu_id`, `role_id`) VALUES (36, 1);
INSERT INTO `sys_roles_menus` (`menu_id`, `role_id`) VALUES (36, 2);
INSERT INTO `sys_roles_menus` (`menu_id`, `role_id`) VALUES (37, 1);
-INSERT INTO `sys_roles_menus` (`menu_id`, `role_id`) VALUES (38, 1);
INSERT INTO `sys_roles_menus` (`menu_id`, `role_id`) VALUES (39, 1);
INSERT INTO `sys_roles_menus` (`menu_id`, `role_id`) VALUES (41, 1);
INSERT INTO `sys_roles_menus` (`menu_id`, `role_id`) VALUES (44, 1);