Files
lpt-be/src/main/java/com/guo/learningprogresstracker/config/WebMvcConfig.java
T
cat_shark 9d3bac8224 feat: 统一 WebMvc 配置,合并 dev/prod 环境配置
- 删除 WebMvcDevConfig 和 WebMvcProdConfig 两个环境特定配置
- 新增统一的 WebMvcConfig,同时包含 CORS 和 SaToken 鉴权拦截器
- CORS 支持通配符 allowedOriginPatterns 与精确 origins 两种模式
- 合并后的配置对所有环境生效,简化部署
2026-07-12 13:43:51 +08:00

54 lines
2.1 KiB
Java

package com.guo.learningprogresstracker.config;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Arrays;
@Configuration
@RequiredArgsConstructor
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {
private final CorsProperties corsProperties;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SaInterceptor(handle -> {
if ("OPTIONS".equalsIgnoreCase(SaHolder.getRequest().getMethod())) {
return;
}
StpUtil.checkLogin();
}))
.addPathPatterns("/**")
.excludePathPatterns("/login");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
String[] origins = corsProperties.getAllowedOrigins();
boolean hasWildcard = origins != null && Arrays.asList(origins).contains("*");
log.info("允许cors的地址配置:{}", Arrays.toString(origins));
if (hasWildcard) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true);
} else {
registry.addMapping("/**")
.allowedOrigins(origins)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(corsProperties.getAllowCredentials() == null || corsProperties.getAllowCredentials());
}
}
}