satoken跨域问题

cccs7 Lv5

在前端发起请求,获取 subject 服务相关数据时,出现了 CORS 问题,刚开始我 在 SpringCloud Gateway 中配置了跨域,但是并没有起作用,我又在相关的微服务中,通过 WebConfig implements WebMvcConfigurer 再次配置了跨域

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:5173")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}

但仍 未通过,然后想到了 我使用了 satoken ,觉得会先一步将请求给打回去,就在 satoken 中配置了 跨域

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* [Sa-Token 权限认证] 配置类
*
*/
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

/**
* 注册 [Sa-Token 全局过滤器]
*/
@Bean
public SaServletFilter getSaServletFilter() {
return new SaServletFilter()

// 指定 [拦截路由] 与 [放行路由]
.addInclude("/**").addExclude("/favicon.ico")

// 认证函数: 每次请求执行
.setAuth(obj -> {
SaManager.getLog().debug("----- 请求path={} 提交token={}", SaHolder.getRequest().getRequestPath(), StpUtil.getTokenValue());
// ...
})

// 异常处理函数:每次认证函数发生异常时执行此函数
.setError(e -> {
return SaResult.error(e.getMessage());
})

// 前置函数:在每次认证函数之前执行
.setBeforeAuth(obj -> {
SaHolder.getResponse()

// ---------- 设置跨域响应头 ----------
// 允许指定域访问跨域资源
.setHeader("Access-Control-Allow-Origin", "*")
// 允许所有请求方式
.setHeader("Access-Control-Allow-Methods", "*")
// 允许的header参数
.setHeader("Access-Control-Allow-Headers", "*")
// 有效时间
.setHeader("Access-Control-Max-Age", "3600")
;

// 如果是预检请求,则立即返回到前端
SaRouter.match(SaHttpMethod.OPTIONS)
.free(r -> System.out.println("--------OPTIONS预检请求,不做处理"))
.back();
})
;
}

}

通过上述配置,最终解决了 跨域问题,同时,收获了一个经验,那就是 在项目集成了别的框架时,需要考虑是不是会影响原本正常的过程,导致原先的配置失效

  • Title: satoken跨域问题
  • Author: cccs7
  • Created at : 2025-03-12 00:22:38
  • Updated at : 2025-03-12 00:28:54
  • Link: https://cs7eric.github.io/2025/03/12/satoken跨域问题/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
satoken跨域问题