当前位置: 首页 > article >正文

详细分析 Spring CORS 配置 (附Demo)

目录

  • 前言
  • 1. 基本知识
  • 2. Demo

前言

基本的Java知识推荐阅读:

  1. java框架 零基础从入门到精通的学习路线 附开源项目面经等(超全)
  2. 【Java项目】实战CRUD的功能整理(持续更新)

原先写过一篇跨域的基本知识:Springboot处理跨域的方式(附Demo)

1. 基本知识

CorsRegistry 是 Spring 框架中用于配置跨源资源共享(CORS)支持的一个类
CORS 允许服务器指示哪些来源(域)可以访问其资源,以防止潜在的跨站点请求伪造(CSRF)攻击

基本的源码如下:

public class CorsRegistry {
    // 存储所有的 CORS 注册信息
    private final List<CorsRegistration> registrations = new ArrayList<>();

    // 构造函数
    public CorsRegistry() {
    }

    // 添加 CORS 映射路径
    public CorsRegistration addMapping(String pathPattern) {
        // 创建一个新的 CorsRegistration 对象
        CorsRegistration registration = new CorsRegistration(pathPattern);
        // 将其添加到 registrations 列表中
        this.registrations.add(registration);
        // 返回创建的注册对象,以便进一步配置
        return registration;
    }

    // 获取所有的 CORS 配置
    protected Map<String, CorsConfiguration> getCorsConfigurations() {
        // 创建一个新的有序 Map,用于存储 CORS 配置
        Map<String, CorsConfiguration> configs = CollectionUtils.newLinkedHashMap(this.registrations.size());
        // 遍历所有的注册信息
        Iterator<CorsRegistration> var2 = this.registrations.iterator();

        while (var2.hasNext()) {
            CorsRegistration registration = var2.next();
            // 将路径模式和对应的 CORS 配置放入 Map 中
            configs.put(registration.getPathPattern(), registration.getCorsConfiguration());
        }

        return configs;
    }
}

上述的源码已经有注释

此处在单独分析下方法

  • CorsRegistry(): 构造函数,初始化 CorsRegistry 对象,创建一个空的 registrations 列表

  • addMapping(String pathPattern)
    接收一个路径模式作为参数,表示要应用 CORS 的路径
    创建一个新的 CorsRegistration 对象并将其添加到 registrations 列表中
    返回该 CorsRegistration 对象,以便进行进一步的 CORS 配置(例如设置允许的来源、方法等)

  • getCorsConfigurations()
    返回一个包含所有 CORS 配置的 Map
    遍历 registrations 列表,将每个 CorsRegistration 的路径模式和其对应的 CORS 配置放入 configs Map 中
    返回最终的 CORS 配置 Map

总的来说:

  1. CorsRegistry 类提供了一个简单而有效的方式来配置应用程序的 CORS 设置
  2. 通过 addMapping 方法,开发人员可以指定需要 CORS 支持的路径,并通过返回的 CorsRegistration 对象进一步配置具体的 CORS 规则
  3. getCorsConfigurations 方法则收集所有注册的信息,方便在应用启动时进行 CORS 配置的应用

2. Demo

这个Demo涉及一个拦截器,基本知识点可以了解:详细分析SpringMvc中HandlerInterceptor拦截器的基本知识(附Demo)

附上一个实战中的Demo:

@Configuration
public class CustomCorsConfiguration implements WebMvcConfigurer {
    // 添加 CORS 映射
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 允许所有接口的跨域请求
                .allowCredentials(true) // 允许发送 Cookie
                .allowedOriginPatterns("*") // 允许所有来源
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"}) // 允许的请求方法
                .allowedHeaders("*") // 允许的请求头
                .exposedHeaders("*"); // 暴露给客户端的响应头
    }
}

常用的方法如下:

函数描述
addMapping(String pathPattern)添加 CORS 映射路径
allowCredentials(boolean allowCredentials)设置是否允许发送 Cookie
allowedOriginPatterns(String… allowedOriginPatterns)设置允许的来源模式
allowedMethods(String… allowedMethods)设置允许的请求方法
allowedHeaders(String… allowedHeaders)设置允许的请求头
exposedHeaders(String… exposedHeaders)设置可以暴露给客户端的响应头

http://www.kler.cn/news/357599.html

相关文章:

  • 5 首页框架及路由配置
  • 二叉树算法之字典树(Trie)详细解读
  • Go 项目如何集成类似mybatisPlus插件呢?GORM走起!!
  • vscode配置ssh远程连接服务器
  • 货币兑换计算器(RMB <=> 美元)
  • 炒股VS炒游戏装备,哪个更好做
  • 有关 C#多表查询学习
  • .NET无侵入式对象池解决方案
  • 免费字体二次贩卖;刮刮乐模拟器;小报童 | 生活周刊 #4
  • @KafkaListener注解
  • 使用docker搭建lnmp运行WordPress
  • 2011年国赛高教杯数学建模B题交巡警服务平台的设置与调度解题全过程文档及程序
  • 光纤光学的基本方程
  • 纯血鸿蒙!
  • BI 的前置计算
  • 2023年ICPC亚洲合肥赛区赛 C. Cyclic Substrings
  • 关于Android12以上的闪屏兼容
  • 深度学习速通系列:中文命名实体识别(NER)数据集大全(含链接)
  • Python 基础语法
  • 【C++】deque(空间适配器))