授權傳送要求
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
從應用程式伺服器或受信任環境傳送至 FCM 的要求必須經過授權。
授權 HTTP v1 傳送要求
視伺服器環境的詳細資料而定,請一併使用下列策略,授權伺服器對 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 就會使用該項變數所指的服務帳戶檔案。
如未設定環境變數,則 ADC 會使用 Compute Engine、Google Kubernetes Engine、App Engine 和 Cloud Functions 針對當中運作的應用程式提供的預設服務帳戶。
如果 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 檔案路徑。這項變數僅適用於您目前的殼層工作階段,因此如果您開啟了新的工作階段,就必須重新設定變數。
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 Library,擷取短期有效的 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 Token (JWT) 驗證要求。詳情請參閱 JSON 網頁符記。
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;
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-16 (世界標準時間)。
[null,null,["上次更新時間: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"]]