You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Google Cloud Functions的CORS以仅允许指定站点访问?

修改Google Cloud Functions(Firebase v2)的CORS配置以限制访问

你的当前代码中,cors: ["*"]会允许所有域名发起跨域请求,存在安全风险。要仅允许你的站点https://example.mygreatsite.net访问,只需将CORS配置里的通配符替换为你的具体域名即可:

修改后的代码如下:

import {onRequest} from "firebase-functions/v2/https";
import * as admin from "firebase-admin";
import {Reference} from "firebase-admin/database";
import {DataSnapshot} from "firebase-admin/database";

.....

exports.myCloudFunction = onRequest({cors: ["https://example.mygreatsite.net"]}, (req, res) => {
  ... 原有业务代码 ...
}); /* End of myCloudFuntion */

补充说明

  • 如果后续需要允许多个域名访问,只需在数组中添加对应的域名即可,比如:cors: ["https://example.mygreatsite.net", "https://another-domain.com"]
  • 该配置仅针对CORS预检请求和跨域请求的Origin校验生效,若要进一步增强安全性,还可以结合请求头校验、身份验证等机制。

内容的提问来源于stack exchange,提问作者Michel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 10:12:01