|
|
@@ -2,7 +2,10 @@ package com.haha.miniapp.config;
|
|
|
|
|
|
import cn.dev33.satoken.interceptor.SaInterceptor;
|
|
|
import cn.dev33.satoken.stp.StpUtil;
|
|
|
+import cn.dev33.satoken.context.SaHolder;
|
|
|
+import cn.dev33.satoken.filter.SaServletFilter;
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.context.annotation.Bean;
|
|
|
import org.springframework.context.annotation.Configuration;
|
|
|
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
|
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
|
|
@@ -11,6 +14,32 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
|
|
@Configuration
|
|
|
public class SaTokenConfig implements WebMvcConfigurer {
|
|
|
|
|
|
+ /**
|
|
|
+ * 注册 Sa-Token 全局过滤器,用于读取小程序的 access_token
|
|
|
+ */
|
|
|
+ @Bean
|
|
|
+ public SaServletFilter getSaServletFilter() {
|
|
|
+ return new SaServletFilter()
|
|
|
+ .addInclude("/**")
|
|
|
+ .addExclude("/login/**", "/health/**", "/callback/**")
|
|
|
+ .setAuth(obj -> {
|
|
|
+ // 从小程序的 access_token 请求头中获取token
|
|
|
+ String accessToken = SaHolder.getRequest().getHeader("access_token");
|
|
|
+ if (accessToken != null && !accessToken.isEmpty()) {
|
|
|
+ // 将 access_token 设置为当前上下文的token
|
|
|
+ StpUtil.setTokenValue(accessToken);
|
|
|
+ log.debug("从小程序请求头中读取到token: {}", accessToken);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 执行登录校验
|
|
|
+ StpUtil.checkLogin();
|
|
|
+ })
|
|
|
+ .setError(e -> {
|
|
|
+ log.warn("Sa-Token认证失败: {}", e.getMessage());
|
|
|
+ return e;
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
@Override
|
|
|
public void addInterceptors(InterceptorRegistry registry) {
|
|
|
// 注册Sa-Token拦截器,拦截所有路径
|
|
|
@@ -20,7 +49,7 @@ public class SaTokenConfig implements WebMvcConfigurer {
|
|
|
if (tokenValue != null && !tokenValue.isEmpty()) {
|
|
|
log.debug("当前请求token: {}, 是否登录: {}", tokenValue, StpUtil.isLogin());
|
|
|
} else {
|
|
|
- log.debug("当前请求未携带token");
|
|
|
+ log.debug("当前请求未携带有效token");
|
|
|
}
|
|
|
|
|
|
// 登录认证:除了指定的接口,其他都需要登录
|
|
|
@@ -28,9 +57,9 @@ public class SaTokenConfig implements WebMvcConfigurer {
|
|
|
}))
|
|
|
.addPathPatterns("/**")
|
|
|
.excludePathPatterns(
|
|
|
- "/login/**", // 登录接口(注意:不包含context-path)
|
|
|
+ "/login/**", // 登录接口
|
|
|
"/health/**", // 健康检查接口
|
|
|
- "/callback/**" // 第三方回调接口(包括微信支付、哈哈平台等)
|
|
|
+ "/callback/**" // 第三方回调接口
|
|
|
);
|
|
|
}
|
|
|
}
|