mirror of
https://gitee.com/lab1024/smart-admin.git
synced 2025-11-12 21:53:48 +08:00
sa-token update
This commit is contained in:
@@ -60,11 +60,6 @@
|
||||
<artifactId>sa-token-redis-jackson</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Sa-Token 整合 jwt -->
|
||||
<dependency>
|
||||
<groupId>cn.dev33</groupId>
|
||||
<artifactId>sa-token-jwt</artifactId>
|
||||
</dependency>
|
||||
<!-- sa-token end -->
|
||||
|
||||
<dependency>
|
||||
|
||||
@@ -26,6 +26,11 @@ public class StringConst {
|
||||
*/
|
||||
public static final String HORIZONTAL = "-";
|
||||
|
||||
/**
|
||||
* 全局通用 冒号
|
||||
*/
|
||||
public static final String COLON = ":";
|
||||
|
||||
/**
|
||||
* 全局通用分隔符
|
||||
*/
|
||||
|
||||
@@ -31,13 +31,7 @@ public class RequestUser {
|
||||
*/
|
||||
private UserTypeEnum userType;
|
||||
|
||||
/**
|
||||
* TODO listen 准备移除
|
||||
* 为了其他地方不报错
|
||||
*/
|
||||
@Deprecated
|
||||
private String ip;
|
||||
|
||||
@Deprecated
|
||||
private String userAgent;
|
||||
}
|
||||
|
||||
@@ -19,28 +19,28 @@ public enum SystemEnvEnum implements BaseEnum {
|
||||
/**
|
||||
* dev
|
||||
*/
|
||||
DEV(SystemEnvironmentNameConst.DEV, "开发环境"),
|
||||
DEV(EnvConst.DEV, "开发环境"),
|
||||
|
||||
/**
|
||||
* test
|
||||
*/
|
||||
TEST(SystemEnvironmentNameConst.TEST, "测试环境"),
|
||||
TEST(EnvConst.TEST, "测试环境"),
|
||||
|
||||
/**
|
||||
* pre
|
||||
*/
|
||||
PRE(SystemEnvironmentNameConst.PRE, "预发布环境"),
|
||||
PRE(EnvConst.PRE, "预发布环境"),
|
||||
|
||||
/**
|
||||
* prod
|
||||
*/
|
||||
PROD(SystemEnvironmentNameConst.PROD, "生产环境");
|
||||
PROD(EnvConst.PROD, "生产环境");
|
||||
|
||||
private final String value;
|
||||
|
||||
private final String desc;
|
||||
|
||||
public static final class SystemEnvironmentNameConst {
|
||||
public static final class EnvConst {
|
||||
public static final String DEV = "dev";
|
||||
public static final String TEST = "test";
|
||||
public static final String PRE = "pre";
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package net.lab1024.sa.common.common.enumeration;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* 用户类型
|
||||
*
|
||||
@@ -9,29 +12,16 @@ package net.lab1024.sa.common.common.enumeration;
|
||||
* @Email lab1024@163.com
|
||||
* @Copyright 1024创新实验室 ( https://1024lab.net ),2012-2022
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum UserTypeEnum implements BaseEnum {
|
||||
|
||||
/**
|
||||
* 管理端 员工用户
|
||||
*/
|
||||
ADMIN_EMPLOYEE(1, "员工");
|
||||
ADMIN_EMPLOYEE(1, "管理端-员工");
|
||||
|
||||
private Integer type;
|
||||
private final Integer value;
|
||||
|
||||
private String desc;
|
||||
|
||||
UserTypeEnum(Integer type, String desc) {
|
||||
this.type = type;
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer getValue() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
private final String desc;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,24 @@
|
||||
package net.lab1024.sa.common.common.interceptor;
|
||||
|
||||
import cn.dev33.satoken.exception.NotLoginException;
|
||||
import cn.dev33.satoken.session.SaSession;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import cn.hutool.extra.servlet.ServletUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.google.common.collect.Lists;
|
||||
import net.lab1024.sa.common.common.annoation.NoNeedLogin;
|
||||
import net.lab1024.sa.common.common.code.UserErrorCode;
|
||||
import net.lab1024.sa.common.common.constant.RequestHeaderConst;
|
||||
import net.lab1024.sa.common.common.domain.RequestUser;
|
||||
import net.lab1024.sa.common.common.domain.ResponseDTO;
|
||||
import net.lab1024.sa.common.common.domain.SystemEnv;
|
||||
import net.lab1024.sa.common.common.enumeration.SystemEnvEnum;
|
||||
import net.lab1024.sa.common.common.enumeration.UserTypeEnum;
|
||||
import net.lab1024.sa.common.common.util.SmartRequestUtil;
|
||||
import net.lab1024.sa.common.module.support.token.TokenService;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -29,17 +39,21 @@ import java.util.List;
|
||||
* @date 2023-07-12 21:56:14
|
||||
*/
|
||||
public abstract class AbstractInterceptor implements HandlerInterceptor {
|
||||
/**
|
||||
* 校验 token
|
||||
*/
|
||||
public abstract void checkSaToken();
|
||||
|
||||
@Autowired
|
||||
private SystemEnv systemEnv;
|
||||
|
||||
/**
|
||||
* Token 获取当前请求用户信息
|
||||
* 校验 token
|
||||
*
|
||||
* @return
|
||||
* @param userId
|
||||
*/
|
||||
public abstract RequestUser getRequestUser();
|
||||
public abstract RequestUser getDevUser(Long userId);
|
||||
|
||||
/**
|
||||
* 校验 当前服务用户类型
|
||||
*/
|
||||
public abstract UserTypeEnum getUserType();
|
||||
|
||||
/**
|
||||
* 拦截路径
|
||||
@@ -83,8 +97,8 @@ public abstract class AbstractInterceptor implements HandlerInterceptor {
|
||||
if (!isHandler) {
|
||||
return true;
|
||||
}
|
||||
// 校验 token 获取当前请求用户信息
|
||||
ResponseDTO<RequestUser> res = this.checkTokenAndGetUser();
|
||||
// 校验 token
|
||||
ResponseDTO<RequestUser> res = this.checkTokenAndGetUser(request);
|
||||
if (res.getOk()) {
|
||||
SmartRequestUtil.setUser(res.getData());
|
||||
return true;
|
||||
@@ -99,7 +113,6 @@ public abstract class AbstractInterceptor implements HandlerInterceptor {
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 sa token
|
||||
* 判断 sa-token 未登录场景值
|
||||
* 自己根据业务在下面 switch 添加分支判断
|
||||
* NotLoginException.NOT_TOKEN 无token
|
||||
@@ -111,13 +124,28 @@ public abstract class AbstractInterceptor implements HandlerInterceptor {
|
||||
* <p>
|
||||
* ps :之所以没有在全局异常里处理 是因为后续还有操作
|
||||
*/
|
||||
public ResponseDTO<RequestUser> checkTokenAndGetUser() {
|
||||
public ResponseDTO<RequestUser> checkTokenAndGetUser(HttpServletRequest request) {
|
||||
/**
|
||||
* 处理【非生产环境】的测试 token ,便于开发调试
|
||||
* 如不需要 可以删除此段判断代码
|
||||
*/
|
||||
if (SystemEnvEnum.PROD != systemEnv.getCurrentEnv()) {
|
||||
String tokenValue = StpUtil.getTokenValue();
|
||||
if (NumberUtils.isDigits(tokenValue)) {
|
||||
RequestUser user = this.getDevUser(NumberUtils.createLong(tokenValue));
|
||||
this.handleRequestIpAndAgent(user, request);
|
||||
// sa token 登录身份临时切换
|
||||
StpUtil.switchTo(TokenService.generateLoginId(user.getUserId(), user.getUserType()));
|
||||
return ResponseDTO.ok(user);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
/**
|
||||
* sa-token 会从当前请求header or body 中获取token
|
||||
* sa-token 会从当前请求 header or body 中获取token
|
||||
* 检验当前会话是否已经登录, 如果未登录,则抛出异常:`NotLoginException`
|
||||
*/
|
||||
this.checkSaToken();
|
||||
StpUtil.checkLogin();
|
||||
} catch (NotLoginException e) {
|
||||
switch (e.getType()) {
|
||||
case NotLoginException.BE_REPLACED:
|
||||
@@ -129,8 +157,13 @@ public abstract class AbstractInterceptor implements HandlerInterceptor {
|
||||
return ResponseDTO.error(UserErrorCode.LOGIN_STATE_INVALID);
|
||||
}
|
||||
}
|
||||
RequestUser requestUser = this.getRequestUser();
|
||||
return ResponseDTO.ok(requestUser);
|
||||
// 校验token的用户类型
|
||||
UserTypeEnum systemUserTypeEnum = this.getUserType();
|
||||
RequestUser user = this.buildCurrentUser(request);
|
||||
if (null == user || systemUserTypeEnum != user.getUserType()) {
|
||||
return ResponseDTO.error(UserErrorCode.LOGIN_STATE_INVALID);
|
||||
}
|
||||
return ResponseDTO.ok(user);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -147,8 +180,35 @@ public abstract class AbstractInterceptor implements HandlerInterceptor {
|
||||
response.flushBuffer();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
|
||||
SmartRequestUtil.remove();
|
||||
/**
|
||||
* build 当前请求用户
|
||||
*
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
public RequestUser buildCurrentUser(HttpServletRequest request) {
|
||||
// 获取额外数据
|
||||
SaSession session = StpUtil.getSession();
|
||||
UserTypeEnum userTypeEnum = (UserTypeEnum) session.get(TokenService.EXTRA_KEY_USER_TYPE);
|
||||
String userName = session.getString(TokenService.EXTRA_KEY_USER_NAME);
|
||||
|
||||
// 当前请求对象
|
||||
RequestUser user = new RequestUser();
|
||||
user.setUserId(TokenService.getUserId((String) StpUtil.getLoginId()));
|
||||
user.setUserName(userName);
|
||||
user.setUserType(userTypeEnum);
|
||||
this.handleRequestIpAndAgent(user, request);
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 当前请求ip agent
|
||||
*
|
||||
* @param requestUser
|
||||
* @param request
|
||||
*/
|
||||
private void handleRequestIpAndAgent(RequestUser requestUser, HttpServletRequest request) {
|
||||
requestUser.setUserAgent(ServletUtil.getHeaderIgnoreCase(request, RequestHeaderConst.USER_AGENT));
|
||||
requestUser.setIp(ServletUtil.getClientIP(request));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package net.lab1024.sa.common.common.util;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import cn.dev33.satoken.context.SaHolder;
|
||||
import cn.dev33.satoken.context.model.SaStorage;
|
||||
import net.lab1024.sa.common.common.domain.RequestUser;
|
||||
|
||||
/**
|
||||
@@ -12,26 +13,28 @@ import net.lab1024.sa.common.common.domain.RequestUser;
|
||||
* @Email lab1024@163.com
|
||||
* @Copyright 1024创新实验室 ( https://1024lab.net )
|
||||
*/
|
||||
@Slf4j
|
||||
public class SmartRequestUtil {
|
||||
|
||||
private static final ThreadLocal<RequestUser> LOCAL = new ThreadLocal<>();
|
||||
private static final String STORAGE_KEY = "user";
|
||||
|
||||
public static void setUser(RequestUser requestUser) {
|
||||
LOCAL.set(requestUser);
|
||||
public static void setUser(RequestUser user) {
|
||||
SaStorage storage = SaHolder.getStorage();
|
||||
storage.set(STORAGE_KEY, user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 当前 token 请求用户
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static RequestUser getUser() {
|
||||
return LOCAL.get();
|
||||
SaStorage storage = SaHolder.getStorage();
|
||||
return storage.getModel(STORAGE_KEY, RequestUser.class);
|
||||
}
|
||||
|
||||
public static Long getUserId() {
|
||||
RequestUser requestUser = getUser();
|
||||
return null == requestUser ? null : requestUser.getUserId();
|
||||
}
|
||||
|
||||
public static void remove() {
|
||||
LOCAL.remove();
|
||||
RequestUser user = getUser();
|
||||
return null != user ? user.getUserId() : null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package net.lab1024.sa.common.config;
|
||||
|
||||
import cn.dev33.satoken.interceptor.SaInterceptor;
|
||||
import com.google.common.collect.Sets;
|
||||
import net.lab1024.sa.common.common.interceptor.AbstractInterceptor;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -10,7 +11,9 @@ import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* web相关配置
|
||||
@@ -33,8 +36,10 @@ public class MvcConfig implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
// 先注册 登录拦截器
|
||||
Set<String> ignoreUrlSet = Sets.newHashSet();
|
||||
if (CollectionUtils.isNotEmpty(interceptorList)) {
|
||||
interceptorList.forEach(e -> {
|
||||
ignoreUrlSet.addAll(e.getIgnoreUrlList());
|
||||
registry.addInterceptor(e).addPathPatterns(e.pathPatterns()).excludePathPatterns(e.getIgnoreUrlList());
|
||||
});
|
||||
}
|
||||
@@ -42,7 +47,7 @@ public class MvcConfig implements WebMvcConfigurer {
|
||||
// 后注册 sa-token 权限拦截器 不需要可以删除
|
||||
if (CollectionUtils.isNotEmpty(saInterceptorList)) {
|
||||
saInterceptorList.forEach(i -> {
|
||||
registry.addInterceptor(i).addPathPatterns("/**");
|
||||
registry.addInterceptor(i).addPathPatterns("/**").excludePathPatterns(new ArrayList<>(ignoreUrlSet));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,7 +198,7 @@ public class SwaggerConfig implements EnvironmentAware, BeanDefinitionRegistryPo
|
||||
Parameter token = new ParameterBuilder().name(RequestHeaderConst.TOKEN)
|
||||
.description("token")
|
||||
.modelRef(new ModelRef("string"))
|
||||
.parameterType("header").defaultValue("1")
|
||||
.parameterType("header").defaultValue("0")
|
||||
.required(false)
|
||||
.build();
|
||||
return Lists.newArrayList(token);
|
||||
|
||||
@@ -34,8 +34,6 @@ public class UrlConfig {
|
||||
@Autowired
|
||||
private RequestMappingHandlerMapping requestMappingHandlerMapping;
|
||||
|
||||
public static List<String> AUTH_URL_LIST = Lists.newArrayList();
|
||||
|
||||
/**
|
||||
* 获取每个方法的请求路径
|
||||
*
|
||||
@@ -81,8 +79,6 @@ public class UrlConfig {
|
||||
Set<String> urlSet = entry.getValue();
|
||||
List<RequestUrlVO> requestUrlList = this.buildRequestUrl(method, urlSet);
|
||||
authUrlList.addAll(requestUrlList);
|
||||
|
||||
AUTH_URL_LIST.addAll(urlSet);
|
||||
}
|
||||
log.info("需要权限校验的URL:{}", authUrlList.stream().map(RequestUrlVO::getUrl).collect(Collectors.toList()));
|
||||
return authUrlList;
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
package net.lab1024.sa.common.config.satoken;
|
||||
|
||||
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
|
||||
import cn.dev33.satoken.stp.StpLogic;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* sa token 配置
|
||||
*
|
||||
* @author: listen
|
||||
* @date: 2023/7/12 20:46
|
||||
*/
|
||||
@Configuration
|
||||
public class SaTokenCommonConfig {
|
||||
|
||||
/**
|
||||
* 整合 jwt
|
||||
*
|
||||
* @return
|
||||
* @see <a>https://sa-token.cc/doc.html#/plugin/jwt-extend</a>
|
||||
*/
|
||||
@Bean
|
||||
public StpLogic getStpLogicJwt() {
|
||||
// Simple 简单模式
|
||||
return new StpLogicJwtForSimple();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package net.lab1024.sa.common.module.support.token;
|
||||
|
||||
import cn.dev33.satoken.session.SaSession;
|
||||
import cn.dev33.satoken.stp.SaLoginModel;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import net.lab1024.sa.common.common.constant.StringConst;
|
||||
@@ -37,31 +38,34 @@ public class TokenService {
|
||||
|
||||
/**
|
||||
* 设置登录模式参数
|
||||
* 具体参数 @see SaLoginModel 属性
|
||||
* 具体参数 {@link SaLoginModel } 属性
|
||||
* 已经写的挺清楚的了
|
||||
*/
|
||||
SaLoginModel loginModel = new SaLoginModel();
|
||||
// 此次登录的客户端设备类型, 用于[同端互斥登录]时指定此次登录的设备类型
|
||||
loginModel.setDevice(String.valueOf(loginDeviceEnum.getDesc()));
|
||||
// 扩展参数 只在 jwt 模式下 有效
|
||||
loginModel.setExtra(EXTRA_KEY_USER_NAME, userName);
|
||||
loginModel.setExtra(EXTRA_KEY_USER_TYPE, userTypeEnum.getValue());
|
||||
|
||||
// 登录
|
||||
String loginId = generateLoginId(userId, userTypeEnum);
|
||||
StpUtil.login(loginId, loginModel);
|
||||
|
||||
// 扩展参数 放入会话中 redis session
|
||||
SaSession session = StpUtil.getSession();
|
||||
session.set(EXTRA_KEY_USER_NAME, userName);
|
||||
session.set(EXTRA_KEY_USER_TYPE, userTypeEnum);
|
||||
return StpUtil.getTokenValue();
|
||||
}
|
||||
|
||||
public static String generateLoginId(Long userId, UserTypeEnum userType) {
|
||||
return userType.getValue() + StringConst.HORIZONTAL + userId;
|
||||
return userType.getValue() + StringConst.COLON + userId;
|
||||
}
|
||||
|
||||
public static Long getUserId(String loginId) {
|
||||
return Long.valueOf(loginId.substring(loginId.indexOf(StringConst.HORIZONTAL) + 1));
|
||||
return Long.valueOf(loginId.substring(loginId.indexOf(StringConst.COLON) + 1));
|
||||
}
|
||||
|
||||
public static Integer getUserType(String loginId) {
|
||||
return Integer.valueOf(loginId.substring(0, loginId.indexOf(StringConst.HORIZONTAL)));
|
||||
return Integer.valueOf(loginId.substring(0, loginId.indexOf(StringConst.COLON)));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user