前后端跨域CORS解决方式

在 Spring Boot 项目中,跨域(Cross-Origin Resource Sharing,CORS)是一个常见的需求,特别是在前后端分离的开发模式中。下面为你详细介绍几种配置全局跨域的方法。

方法一:使用CorsFilter过滤器

这种方法通过创建一个CorsFilter过滤器来实现全局跨域配置。以下是具体步骤和示例代码:

步骤
  1. 创建一个配置类,在该类中定义CorsFilter过滤器。
  2. 配置CorsConfiguration对象,设置允许的请求来源、请求方法、请求头、允许携带凭证等信息。
  3. CorsConfiguration对象封装到UrlBasedCorsConfigurationSource中,并指定过滤的路径。
  4. UrlBasedCorsConfigurationSource作为参数创建CorsFilter过滤器,并将其注册到 Spring 容器中。
示例代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        // 1. 创建CorsConfiguration对象
        CorsConfiguration config = new CorsConfiguration();
        // 允许任何域名进行跨域调用
        config.addAllowedOriginPattern("*");
        // 允许任何请求头
        config.addAllowedHeader("*");
        // 允许任何方法(POST、GET等)
        config.addAllowedMethod("*");
        // 允许携带凭证
        config.setAllowCredentials(true);

        // 2. 创建UrlBasedCorsConfigurationSource对象
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对所有接口都有效
        source.registerCorsConfiguration("/**", config);

        // 3. 创建CorsFilter对象
        return new CorsFilter(source);
    }
}

方法二:实现WebMvcConfigurer接口

通过实现WebMvcConfigurer接口,重写addCorsMappings方法来配置全局跨域。以下是具体步骤和示例代码:

步骤
  1. 创建一个配置类,实现WebMvcConfigurer接口。
  2. 重写addCorsMappings方法,在该方法中配置跨域映射。
  3. 设置允许的请求来源、请求方法、请求头、允许携带凭证等信息。
示例代码
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 WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                // 允许任何域名进行跨域调用
                .allowedOriginPatterns("*")
                // 允许任何请求头
                .allowedHeaders("*")
                // 允许任何方法(POST、GET等)
                .allowedMethods("*")
                // 允许携带凭证
                .allowCredentials(true);
    }
}

方法三:使用 Spring Security(如果项目中使用了 Spring Security)

如果你的项目中使用了 Spring Security,需要在安全配置类中配置跨域。以下是具体步骤和示例代码:

步骤
  1. 创建一个安全配置类,继承WebSecurityConfigurerAdapter
  2. 重写configure(HttpSecurity http)方法,在该方法中配置跨域。
  3. 使用cors()方法启用跨域支持,并自定义跨域配置。
示例代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
           .cors().configurationSource(corsConfigurationSource())
           .and()
           // 其他安全配置
           .authorizeRequests()
           .anyRequest().permitAll();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

以上三种方法都可以实现 Spring Boot 项目的全局跨域配置,你可以根据项目的具体情况选择合适的方法。