【SpringBoot】WebConfig 跨域配置详细说明

发布于:2025-05-01 ⋅ 阅读:(58) ⋅ 点赞:(0)

功能概述

WebConfig 是一个 Spring Boot 配置类,主要用于配置跨域资源共享 (CORS) 策略,解决前端应用访问后端 API 时的跨域问题。

package com.example.springboot.config;//根据个人程序需修改

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;

/**
 * Web配置类
 * 用于配置跨域资源共享(CORS)等Web相关设置
 */
@Configuration
public class WebConfig {

    /**
     * 配置跨域资源共享
     * 允许前端应用访问后端API
     * 
     * @return CorsFilter
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();   
        // 允许所有域名进行跨域调用
        config.addAllowedOriginPattern("*");		          
        // 允许跨越发送cookie
        config.setAllowCredentials(true);			          
        // 放行全部原始头信息
        config.addAllowedHeader("*");				          
        // 允许所有请求方法跨域调用
        config.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

配置详情

跨域配置 (CORS)

通过 corsFilter() 方法配置了一个全局的 CORS 过滤器:

  1. 允许的源:

    • config.addAllowedOriginPattern("*"): 允许所有域名进行跨域访问
    • 注意:在生产环境中,建议替换为具体的前端域名而非通配符,以增强安全性
  2. 凭证支持:

    • config.setAllowCredentials(true): 允许跨域请求携带认证信息(如 cookies)
  3. 请求头设置:

    • config.addAllowedHeader("*"): 允许所有请求头信息
  4. HTTP 方法:

    • config.addAllowedMethod("*"): 允许所有 HTTP 方法(GET, POST, PUT, DELETE 等)
  5. 路径匹配:

    • source.registerCorsConfiguration("/**", config): 对所有路径应用此 CORS 配置

使用建议

  1. 生产环境调整:

    • 建议将 addAllowedOriginPattern("*") 替换为具体的前端域名,例如:
      config.addAllowedOriginPattern("https://yourdomain.com");
      config.addAllowedOriginPattern("https://yourotherdomain.com");
      
  2. 安全性考虑:

    • 如果不需要凭证,应将 setAllowCredentials(false) 以提高安全性
    • 可以根据实际需求限制允许的 HTTP 方法和请求头
  3. 测试环境:

    • 当前配置非常适合开发和测试环境
    • 允许所有来源、方法和头部的配置便于前端开发调试

集成方式

该配置类会自动被 Spring Boot 加载,无需额外配置。只需确保该类位于主应用类所在的包或其子包中。

版本兼容性

  • 适用于 Spring Boot 2.4.x 及以上版本
  • addAllowedOriginPattern 方法在 Spring Boot 2.4.0 引入,替代了之前版本的 addAllowedOrigin

转载吱一声~


网站公告

今日签到

点亮在社区的每一天
去签到