解决了除GET方法外的跨域问题,重写了spring security 配置文件

This commit is contained in:
puzvv
2025-12-20 01:36:14 +08:00
parent fbf730d600
commit 2b8f2307b7
3 changed files with 30 additions and 11 deletions

View File

@@ -27,7 +27,7 @@ public class CorsConfig {
config.addAllowedHeader("*");
// 允许的请求方法
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.addAllowedMethod("*");
// 允许发送Cookie
config.setAllowCredentials(true);

View File

@@ -6,6 +6,11 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
@Configuration
@EnableWebSecurity
@@ -14,20 +19,33 @@ public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// 启用跨域配置
.cors(cors -> cors.configurationSource(request -> new org.springframework.web.cors.CorsConfiguration().applyPermitDefaultValues()))
// 禁用默认的登录表单和HTTP基本认证
.formLogin(form -> form.disable())
.httpBasic(basic -> basic.disable())
// 允许所有请求通过,取消默认登录验证
// 启用跨域配置
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
// 禁用默认的登录表单和HTTP基本认证
.formLogin(form -> form.disable())
.httpBasic(basic -> basic.disable())
// 允许所有请求通过,取消默认登录验证
// .authorizeHttpRequests((authz) -> authz
// .anyRequest().permitAll()
// )
// 禁用CSRF保护
.csrf(csrf -> csrf.disable())
// 设置会话创建策略为无状态
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
// 禁用CSRF保护
.csrf(csrf -> csrf.disable())
// 设置会话创建策略为无状态
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOriginPatterns(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}

View File

@@ -28,6 +28,7 @@ import java.util.Map;
@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin
public class UserController {
@Autowired