授权发送请求
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
从您的应用服务器或受信任环境发送到 FCM 的请求必须经过授权。
为 HTTP v1 发送请求 (send request) 提供授权
根据服务器环境的详细信息,您可以组合使用以下策略为服务器向 Firebase 服务发送的请求提供授权:
- Google 应用默认凭证 (ADC)
- 服务账号 JSON 文件
- 源自服务账号的短期有效的 OAuth 2.0 访问令牌
如果您的应用在 Compute Engine、Google Kubernetes Engine、App Engine 或 Cloud Functions(包括 Cloud Functions for Firebase)上运行,请使用应用默认凭证 (ADC)。ADC 会使用您现有的默认服务账号来获取用于为请求提供授权的凭据,并可通过环境变量 GOOGLE_APPLICATION_CREDENTIALS 实现灵活的本地测试。为了最大限度地自动化授权流程,请将 ADC 与 Admin SDK 服务器库搭配使用。
如果您的应用在非 Google 服务器环境中运行,则需要从 Firebase 项目下载服务账号 JSON 文件。只要您有权访问包含私钥文件的文件系统,就可以通过环境变量 GOOGLE_APPLICATION_CREDENTIALS 利用这些手动获取的凭据为请求提供授权。如果您没有此类文件访问权限,则必须在代码中引用服务账号文件,但这样做存在凭据泄露的风险,因此请务必谨慎。
使用 ADC 提供凭据
Google 应用默认凭证 (ADC) 按以下顺序查找您的凭证:
ADC 检查是否已设置环境变量 GOOGLE_APPLICATION_CREDENTIALS。如果设置了该变量,ADC 就会使用该变量指向的服务账号文件。
如果未设置环境变量,则对于在 Compute Engine、Google Kubernetes Engine、App Engine 和 Cloud Functions 上运行的应用,ADC 会使用这些服务提供的默认服务账号。
如果 ADC 无法使用上述任何凭据,系统会抛出一个错误。
以下 Admin SDK 代码示例展示了该策略。该示例并未明确指定应用凭据。但是,只要设置了该环境变量,或者只要应用在 Compute Engine、Google Kubernetes Engine、App Engine 或 Cloud Functions 上运行,ADC 便能够隐式查找凭据。
Node.js
admin.initializeApp({
credential: admin.credential.applicationDefault(),
});
Java
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.getApplicationDefault())
.setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
.build();
FirebaseApp.initializeApp(options);
Python
default_app = firebase_admin.initialize_app()
Go
app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
C#
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.GetApplicationDefault(),
});
手动提供凭据
Firebase 项目支持 Google 服务账号,您可以使用这些账号从应用服务器或受信任环境调用 Firebase 服务器 API。如果您是在本地编写代码,或是在本地部署您的应用,则可以使用通过此服务账号获取的凭据来对服务器请求进行授权。
如需对服务账号进行身份验证并授予其访问 Firebase 服务的权限,您必须生成 JSON 格式的私钥文件。
如需为您的服务账号生成私钥文件,请执行以下操作:
在 Firebase 控制台中,依次打开设置 > 服务账号。
点击生成新的私钥,然后点击生成密钥进行确认。
妥善存储包含密钥的 JSON 文件。
通过服务账号进行授权时,有两种方式可为您的应用提供凭据。您可以设置 GOOGLE_APPLICATION_CREDENTIALS 环境变量,也可以在代码中明确传递服务账号密钥的路径。第一种方式更为安全,因此强烈推荐使用此方式。
如需设置该环境变量,请执行以下操作:
将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为包含服务账号密钥的 JSON 文件的路径:此变量仅适用于当前的 Shell 会话,因此请在开始新的会话时重新设置该变量。
Linux 或 macOS
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
Windows
使用 PowerShell:
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"
完成上述步骤后,应用默认凭据 (ADC) 便能隐式确定您的凭据,这样,在非 Google 环境中测试或运行应用时,您就能使用服务账号凭据。
使用凭据来创建访问令牌
除非您使用自动处理授权的 Admin SDK,否则均需创建访问令牌并将其添加到发送请求中。
将您的 Firebase 凭据与适用于您的偏好语言的 Google Auth 库结合使用,以检索短期有效的 OAuth 2.0 访问令牌:
node.js
function getAccessToken() {
return new Promise(function(resolve, reject) {
const key = require('../placeholders/service-account.json');
const jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
SCOPES,
null
);
jwtClient.authorize(function(err, tokens) {
if (err) {
reject(err);
return;
}
resolve(tokens.access_token);
});
});
}
在此示例中,Google API 客户端库使用 JSON Web 令牌 (JWT) 对请求进行身份验证。有关详情,请参阅 JSON Web 令牌。
Python
def _get_access_token():
"""Retrieve a valid access token that can be used to authorize requests.
:return: Access token.
"""
credentials = service_account.Credentials.from_service_account_file(
'service-account.json', scopes=SCOPES)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
return credentials.token
Java
private static String getAccessToken() throws IOException {
GoogleCredentials googleCredentials = GoogleCredentials
.fromStream(new FileInputStream("service-account.json"))
.createScoped(Arrays.asList(SCOPES));
googleCredentials.refresh();
return googleCredentials.getAccessToken().getTokenValue();
}
在您的访问令牌到期后,系统会自动调用令牌刷新方法以检索更新的访问令牌。
如需授予访问 FCM 的权限,则需请求 https://www.googleapis.com/auth/firebase.messaging
范围。
如需将访问令牌添加到 HTTP 请求标头中,请使用以下代码:
以 Authorization: Bearer <access_token>
格式将令牌添加为 Authorization
标头的值:
node.js
headers: {
'Authorization': 'Bearer ' + accessToken
}
Python
headers = {
'Authorization': 'Bearer ' + _get_access_token(),
'Content-Type': 'application/json; UTF-8',
}
Java
URL url = new URL(BASE_URL + FCM_SEND_ENDPOINT);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Authorization", "Bearer " + getServiceAccountAccessToken());
httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
return httpURLConnection;
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-16。
[null,null,["最后更新时间 (UTC):2025-08-16。"],[],[],null,["\u003cbr /\u003e\n\n\nRequests sent to FCM from your app server or trusted environment\nmust be authorized.\n\nAuthorize HTTP v1 send requests\n\nDepending on the details of your\nserver environment, use a combination of these strategies to authorize server\nrequests to Firebase services:\n\n- Google Application Default Credentials (ADC)\n- A service account JSON file\n- A short-lived OAuth 2.0 access token derived from a service account\n\n**If your application is running on Compute Engine,\nGoogle Kubernetes Engine, App Engine, or Cloud Functions**\n(including Cloud Functions for Firebase), use Application Default Credentials (ADC). ADC uses your existing default service\naccount to obtain credentials to authorize requests, and ADC enables\nflexible local testing via the environment variable\n\u003cvar translate=\"no\"\u003eGOOGLE_APPLICATION_CREDENTIALS\u003c/var\u003e. For the fullest automation of the\nauthorization flow, use ADC together with Admin SDK server libraries.\n\n**If your application is running on a non-Google server environment** ,\nyou'll need to download a service account JSON file from your Firebase project.\nAs long as you have access to a file system containing the\nprivate key file, you can use the environment variable\n\u003cvar translate=\"no\"\u003eGOOGLE_APPLICATION_CREDENTIALS\u003c/var\u003e to authorize requests\nwith these manually obtained credentials. If you lack\nsuch file access, you must reference the service account file in your code---\nwhich should be done with extreme care due to the risk of exposing your credentials.\n\nProvide credentials using ADC\n\nGoogle Application Default Credentials (ADC) checks for your credentials\nin the following order:\n\n1. ADC checks whether the environment variable\n \u003cvar translate=\"no\"\u003eGOOGLE_APPLICATION_CREDENTIALS\u003c/var\u003e is set. If the variable is set,\n ADC uses the service account file that the variable points to.\n\n2. If the environment variable isn't set, ADC uses the default service account\n that Compute Engine, Google Kubernetes Engine, App Engine,\n and Cloud Functions provide for applications that run on those services.\n\n3. If ADC can't use either of the above credentials, the system throws an error.\n\nThe following Admin SDK code example illustrates this strategy. The example\ndoesn't explicitly specify the application credentials. However, ADC is able to\nimplicitly find the credentials as long as the environment variable is set, or\nas long as the application is running on Compute Engine,\nGoogle Kubernetes Engine, App Engine, or Cloud Functions. \n\nNode.js \n\n admin.initializeApp({\n credential: admin.credential.applicationDefault(),\n });\n\nJava \n\n FirebaseOptions options = FirebaseOptions.builder()\n .setCredentials(GoogleCredentials.getApplicationDefault())\n .setDatabaseUrl(\"https://\u003cDATABASE_NAME\u003e.firebaseio.com/\")\n .build();\n\n FirebaseApp.initializeApp(options);\n\nPython \n\n default_app = firebase_admin.initialize_app()\n\nGo \n\n app, err := firebase.NewApp(context.Background(), nil)\n if err != nil {\n \tlog.Fatalf(\"error initializing app: %v\\n\", err)\n } \n https://github.com/firebase/firebase-admin-go/blob/26dec0b7589ef7641eefd6681981024079b8524c/snippets/init.go#L60-L63\n\nC# \n\n FirebaseApp.Create(new AppOptions()\n {\n Credential = GoogleCredential.GetApplicationDefault(),\n });\n\nProvide credentials manually\n\nFirebase projects support Google\n[service accounts](//console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk),\nwhich you can use to call Firebase\nserver APIs from your app server or trusted environment. If you're developing\ncode locally or deploying your application on-premises,\nyou can use credentials obtained\nvia this service account to authorize server requests.\n\nTo authenticate a service account and authorize it\nto access Firebase services, you must generate a private key file in JSON\nformat.\n\n**To generate a private key file for your service account:**\n\n1. In the Firebase console, open\n **Settings \\\u003e [Service Accounts](//console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk)**.\n\n2. Click **Generate New Private Key** , then confirm by clicking **Generate Key**.\n\n3. Securely store the JSON file containing the key.\n\nWhen authorizing via a service account, you have two choices for providing the\ncredentials to your application. You can either set the\n\u003cvar translate=\"no\"\u003eGOOGLE_APPLICATION_CREDENTIALS\u003c/var\u003e environment variable, or you can\nexplicitly pass the path to the service account key in code.\nThe first option is more secure and is strongly recommended.\n\n**To set the environment variable:**\n\nSet the environment variable \u003cvar translate=\"no\"\u003eGOOGLE_APPLICATION_CREDENTIALS\u003c/var\u003e\nto the file path of the JSON file that contains your service account key.\nThis variable only applies to your current shell session, so if you open\na new session, set the variable again. \n\nLinux or macOS \n\n export GOOGLE_APPLICATION_CREDENTIALS=\"/home/user/Downloads/service-account-file.json\"\n\nWindows\n\nWith PowerShell: \n\n $env:GOOGLE_APPLICATION_CREDENTIALS=\"C:\\Users\\username\\Downloads\\service-account-file.json\"\n\nAfter you've completed the above steps, Application Default Credentials (ADC)\nis able to implicitly determine your credentials, allowing you to use service\naccount credentials when testing or running in non-Google environments.\n\nUse credentials to mint access tokens\n\nUnless you are using the\n[Admin SDK](/docs/cloud-messaging/server#firebase-admin-sdk-for-fcm),\nwhich handle authorization automatically, you'll need to mint the access token\nand add it to send requests.\n\nUse your Firebase credentials together with\nthe [Google Auth Library](https://github.com/googleapis?q=auth)\nfor your preferred language to retrieve a short-lived OAuth 2.0 access token: \n\nnode.js \n\n function getAccessToken() {\n return new Promise(function(resolve, reject) {\n const key = require('../placeholders/service-account.json');\n const jwtClient = new google.auth.JWT(\n key.client_email,\n null,\n key.private_key,\n SCOPES,\n null\n );\n jwtClient.authorize(function(err, tokens) {\n if (err) {\n reject(err);\n return;\n }\n resolve(tokens.access_token);\n });\n });\n } \n https://github.com/firebase/quickstart-nodejs/blob/55f2ff5c17c730f7fc352f51a5264011de92fed0/messaging/index.js#L22-L40\n\nIn this example, the Google API client library authenticates the request with\na JSON web token, or JWT. For more information, see\n[JSON web tokens](//github.com/googleapis/google-auth-library-nodejs/blob/d8c70b9d858e1ef07cb8ef2b5d5d560ac2b2600a/README.md#json-web-tokens).\n\nPython \n\n def _get_access_token():\n \"\"\"Retrieve a valid access token that can be used to authorize requests.\n\n :return: Access token.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_file(\n 'service-account.json', scopes=SCOPES)\n request = google.auth.transport.requests.Request()\n credentials.refresh(request)\n return credentials.token \n https://github.com/firebase/quickstart-python/blob/2c68e7c5020f4dbb072cca4da03dba389fbbe4ec/messaging/messaging.py#L26-L35\n\nJava \n\n private static String getAccessToken() throws IOException {\n GoogleCredentials googleCredentials = GoogleCredentials\n .fromStream(new FileInputStream(\"service-account.json\"))\n .createScoped(Arrays.asList(SCOPES));\n googleCredentials.refresh();\n return googleCredentials.getAccessToken().getTokenValue();\n } \n https://github.com/firebase/quickstart-java/blob/254dd24fbc89e6b49e6c84ecbbcc1ba31975392c/messaging/src/main/java/com/google/firebase/quickstart/Messaging.java#L56-L62\n\nAfter your access token expires, the token refresh method is called\nautomatically to retrieve an updated access token.\n\nTo authorize access to FCM, request the scope\n`https://www.googleapis.com/auth/firebase.messaging`.\n\n**To add the access token to an HTTP request header:**\n\nAdd the token as the value of the `Authorization` header in the format\n`Authorization: Bearer \u003caccess_token\u003e`: \n\nnode.js \n\n headers: {\n 'Authorization': 'Bearer ' + accessToken\n } \n https://github.com/firebase/quickstart-nodejs/blob/55f2ff5c17c730f7fc352f51a5264011de92fed0/messaging/index.js#L55-L57\n\nPython \n\n headers = {\n 'Authorization': 'Bearer ' + _get_access_token(),\n 'Content-Type': 'application/json; UTF-8',\n } \n https://github.com/firebase/quickstart-python/blob/2c68e7c5020f4dbb072cca4da03dba389fbbe4ec/messaging/messaging.py#L45-L48\n\nJava \n\n URL url = new URL(BASE_URL + FCM_SEND_ENDPOINT);\n HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();\n httpURLConnection.setRequestProperty(\"Authorization\", \"Bearer \" + getServiceAccountAccessToken());\n httpURLConnection.setRequestProperty(\"Content-Type\", \"application/json; UTF-8\");\n return httpURLConnection; \n https://github.com/firebase/snippets-java/blob/7051da2745f8f95b176c9c6347e0bb0db3de1112/admin/src/main/java/com/google/firebase/example/FirebaseMessagingSnippets.java#L243-L247"]]