SpringBoot3中跨域问题解决

问题

SpringBoot3 中处理跨域请求

异常

浏览器在 localhost:3000 地址请求后端 http://127.0.0.1:8080 时, 报错提示 CORS 问题.
默认使用 Get 请求正常, 其他会提示.
使用 SpringBoot 3.4.2 版本配合 SpringSecurity 配置

Access to fetch at 'http://127.0.0.1:8080/todo-task/list' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

解决

需要在 Spring Security 配置以下内容…


/**
 * Spring Security 配置
 *
 * @author Jion
 */
@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    private final CustomAuthenticationEntryPoint unauthorizedHandler;


    /**
     * 配置过滤器链
     *
     * @param http 请求
     * @return 过滤器链
     * @throws Exception 抛出异常
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		// 一些其他配置等...
		
        // 跨域请求
        http.cors(corsConfigurer -> corsConfigurer.configurationSource(corsConfigurationSource()));
        return http.build();
    }


    /**
     * 跨域配置, 仅在开发环境有必要.
     * 如果是发布之后, 桌面应用不会产生跨域问题.
     */
    @Bean
    public UrlBasedCorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 允许本地域名访问
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000", "http://127.0.0.1:3000"));
        // 允许被本地域名访问
        configuration.setAllowedOriginPatterns(Arrays.asList("http://localhost:3000/**", "http://127.0.0.1:3000/**"));
        // 允许所有请求方法
        configuration.setAllowedMethods(List.of("*"));
        // 允许所有请求头
        configuration.setAllowedHeaders(List.of("*"));
        // 允许所有响应头
        configuration.setExposedHeaders(List.of("*"));
        // 允许携带凭证
        configuration.setAllowCredentials(true);
        // 跨域请求配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 匹配所有请求路径
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

你可能感兴趣的:(spring,boot)