Skip to content

Commit d8123d6

Browse files
committed
fix: 修复刷新后丢失token问题,没有从redis拿到实际数据
1 parent f695941 commit d8123d6

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/main/java/com/xiaozhi/common/config/SaTokenConfig.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,14 @@
22

33
import cn.dev33.satoken.interceptor.SaInterceptor;
44
import cn.dev33.satoken.stp.StpUtil;
5+
import com.xiaozhi.entity.SysUser;
6+
import com.xiaozhi.service.SysUserService;
7+
import com.xiaozhi.utils.CmsUtils;
8+
import jakarta.annotation.Resource;
9+
import jakarta.servlet.http.HttpServletRequest;
10+
import jakarta.servlet.http.HttpServletResponse;
511
import org.springframework.context.annotation.Configuration;
12+
import org.springframework.web.servlet.HandlerInterceptor;
613
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
714
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
815

@@ -14,6 +21,9 @@
1421
@Configuration
1522
public class SaTokenConfig implements WebMvcConfigurer {
1623

24+
@Resource
25+
private SysUserService userService;
26+
1727
/**
1828
* 注册Sa-Token拦截器
1929
*/
@@ -23,5 +33,45 @@ public void addInterceptors(InterceptorRegistry registry) {
2333
// 不需要登录的接口请使用 @SaIgnore 注解标注
2434
registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))
2535
.addPathPatterns("/api/**");
36+
37+
// 注册用户信息设置拦截器,在sa-token之后执行
38+
registry.addInterceptor(new UserSetupInterceptor(userService))
39+
.addPathPatterns("/api/**")
40+
.order(1); // 设置较高的优先级,确保在sa-token之后执行
41+
}
42+
43+
/**
44+
* 用户信息设置拦截器
45+
* 从sa-token获取登录用户ID,查询用户信息并设置到Request属性中
46+
*/
47+
private static class UserSetupInterceptor implements HandlerInterceptor {
48+
private final SysUserService userService;
49+
50+
public UserSetupInterceptor(SysUserService userService) {
51+
this.userService = userService;
52+
}
53+
54+
@Override
55+
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
56+
// 检查是否已登录
57+
if (StpUtil.isLogin()) {
58+
try {
59+
// 从sa-token获取登录用户ID
60+
Object loginId = StpUtil.getLoginId();
61+
if (loginId != null) {
62+
Integer userId = Integer.valueOf(loginId.toString());
63+
// 查询用户信息
64+
SysUser user = userService.selectUserByUserId(userId);
65+
if (user != null) {
66+
// 设置用户信息到Request属性
67+
CmsUtils.setUser(request, user);
68+
}
69+
}
70+
} catch (Exception e) {
71+
// 忽略异常,继续处理请求
72+
}
73+
}
74+
return true;
75+
}
2676
}
2777
}

0 commit comments

Comments
 (0)