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

如何在Firebase Cloud Function中导入Google Cloud凭证?

问题描述

我在Firebase Cloud Function中配置Google Cloud Translation时遇到权限问题。本地使用key.json凭证运行演示代码正常,但部署到Firebase Cloud Function后,函数触发执行时返回错误:

Error: 7 PERMISSION_DENIED: Cloud IAM permission

我仅在部署的函数代码中添加了return语句以符合Firebase要求,想知道如何在Firebase Cloud Function中正确配置凭证。

解决方案

在Firebase Cloud Function中无需手动导入key.json,因为函数运行时会自动使用项目的默认服务账号,只需为该账号赋予Google Cloud Translation的权限即可,具体步骤如下:

1. 确认Firebase Cloud Function的默认服务账号

Firebase Cloud Function使用的默认服务账号格式为:
[你的Firebase项目ID]@appspot.gserviceaccount.com
你可以在Firebase控制台的「设置」→「服务账号」页面找到该账号。

2. 为服务账号添加翻译权限

通过gcloud CLI或Google Cloud控制台为上述账号添加Cloud Translation API User权限:

使用gcloud CLI命令:

gcloud projects add-iam-policy-binding languagetwo-cd94d \
  --member="serviceAccount:languagetwo-cd94d@appspot.gserviceaccount.com" \
  --role="roles/cloudtranslate.user"

通过Google Cloud控制台操作:

  • 打开Google Cloud控制台的IAM页面
  • 找到目标服务账号
  • 点击「编辑」→「添加角色」,搜索并选择「Cloud Translation API User」,保存更改

3. 优化函数代码(可选)

将客户端初始化移到函数外部,避免每次触发重复初始化,同时简化代码结构:

// 全局初始化翻译客户端,仅执行一次
const { TranslationServiceClient } = require('@google-cloud/translate');
const translationClient = new TranslationServiceClient();
const projectId = 'languagetwo-cd94d';
const location = 'global';

exports.ENtranslateES = functions.firestore.document('Users/{userID}/English/Translation_Request').onUpdate(async (change) => {
    // 可根据实际需求从Firestore变更中获取待翻译文本
    const text = 'Hello, world!';
    
    const request = {
        parent: `projects/${projectId}/locations/${location}`,
        contents: [text],
        mimeType: 'text/plain',
        sourceLanguageCode: 'en',
        targetLanguageCode: 'es',
    };

    const [response] = await translationClient.translateText(request);
    response.translations.forEach(translation => {
        console.log(`Translation: ${translation.translatedText}`);
    });

    // 若需将翻译结果写入Firestore,在此添加逻辑并返回对应的Promise
    return null;
});

关键说明

Firebase Cloud Function部署在Google Cloud基础设施上,运行时会自动关联项目的默认服务账号,无需手动设置GOOGLE_APPLICATION_CREDENTIALS环境变量或导入key文件。手动导入凭证不仅多余,还可能引发安全风险或权限冲突。

内容的提问来源于stack exchange,提问作者Thomas David Kehoe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:50:44