在這個範例中,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)returncredentials.token
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-03 (世界標準時間)。"],[],[],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"]]