با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
درخواستهایی که از سرور برنامه یا محیط مورد اعتماد شما به FCM ارسال میشوند باید مجاز باشند.
درخواست های ارسال HTTP v1 را مجاز کنید
بسته به جزئیات محیط سرور خود، از ترکیبی از این استراتژیها برای مجاز کردن درخواستهای سرور به خدمات Firebase استفاده کنید:
اعتبار پیش فرض برنامه Google (ADC)
فایل JSON حساب سرویس
یک نشانه دسترسی کوتاه مدت OAuth 2.0 که از یک حساب سرویس مشتق شده است
اگر برنامه شما روی Compute Engine ، Google Kubernetes Engine ، App Engine یا توابع Cloud اجرا می شود (از جمله Cloud Functions for Firebase )، از اعتبارنامه پیش فرض برنامه (ADC) استفاده کنید. ADC از حساب سرویس پیشفرض موجود شما برای دریافت اعتبار برای تأیید درخواستها استفاده میکند و ADC آزمایش محلی انعطافپذیر را از طریق متغیر محیطی GOOGLE_APPLICATION_CREDENTIALS فعال میکند. برای اتوماسیون کامل جریان مجوز، از ADC همراه با کتابخانه های سرور Admin SDK استفاده کنید.
اگر برنامه شما در یک محیط سرور غیر Google اجرا می شود ، باید یک فایل JSON حساب سرویس را از پروژه Firebase خود دانلود کنید. تا زمانی که به یک سیستم فایل حاوی فایل کلید خصوصی دسترسی دارید، میتوانید از متغیر محیطی GOOGLE_APPLICATION_CREDENTIALS برای مجوز دادن به درخواستها با این اعتبارنامههای دستی استفاده کنید. اگر دسترسی به چنین فایلی ندارید، باید فایل حساب سرویس را در کد خود ارجاع دهید - که به دلیل خطر افشای اعتبار شما باید با دقت زیادی انجام شود.
با استفاده از ADC اعتبارنامه را ارائه دهید
اعتبارنامه پیش فرض برنامه Google (ADC) اعتبار شما را به ترتیب زیر بررسی می کند:
ADC بررسی می کند که آیا متغیر محیطی GOOGLE_APPLICATION_CREDENTIALS تنظیم شده است یا خیر. اگر متغیر تنظیم شده باشد، ADC از فایل حساب سرویس که متغیر به آن اشاره می کند استفاده می کند.
اگر متغیر محیط تنظیم نشده باشد، ADC از حساب سرویس پیشفرض استفاده میکند که Compute Engine ، Google Kubernetes Engine ، App Engine و Cloud Functions برای برنامههایی که روی آن سرویسها اجرا میشوند، ارائه میکنند.
اگر ADC نتواند از هیچ یک از اعتبارنامه های بالا استفاده کند، سیستم خطا می دهد.
مثال کد Admin SDK زیر این استراتژی را نشان می دهد. مثال به صراحت اعتبار برنامه را مشخص نمی کند. با این حال، ADC میتواند اعتبارنامهها را تا زمانی که متغیر محیط تنظیم شده است، یا تا زمانی که برنامه در Compute Engine ، Google Kubernetes Engine ، App Engine یا Cloud Functions اجرا میشود، پیدا کند.
پروژههای Firebase از حسابهای سرویس Google پشتیبانی میکنند که میتوانید از آنها برای فراخوانی APIهای سرور Firebase از سرور برنامه یا محیط مورد اعتماد خود استفاده کنید. اگر در حال توسعه کد به صورت محلی یا نصب برنامه خود در محل هستید، می توانید از اعتبارنامه های به دست آمده از طریق این حساب سرویس برای تأیید درخواست های سرور استفاده کنید.
برای احراز هویت یک حساب سرویس و اجازه دسترسی به خدمات Firebase، باید یک فایل کلید خصوصی با فرمت JSON ایجاد کنید.
برای ایجاد یک فایل کلید خصوصی برای حساب سرویس خود:
روی Generate New Private Key کلیک کنید، سپس با کلیک روی Generate Key تأیید کنید.
فایل JSON حاوی کلید را ایمن ذخیره کنید.
هنگام مجوز دادن از طریق یک حساب سرویس، دو انتخاب برای ارائه اعتبارنامه به برنامه خود دارید. میتوانید متغیر محیطی GOOGLE_APPLICATION_CREDENTIALS را تنظیم کنید، یا میتوانید مسیر کلید حساب سرویس را به صورت واضح در کد ارسال کنید. گزینه اول امن تر است و به شدت توصیه می شود.
برای تنظیم متغیر محیطی:
متغیر محیطی GOOGLE_APPLICATION_CREDENTIALS را روی مسیر فایل فایل JSON که حاوی کلید حساب سرویس شما است، تنظیم کنید. این متغیر فقط برای جلسه پوسته فعلی شما اعمال می شود، بنابراین اگر جلسه جدیدی را باز کردید، متغیر را دوباره تنظیم کنید.
پس از تکمیل مراحل بالا، اعتبارنامه پیشفرض برنامه (ADC) میتواند به طور ضمنی اعتبار شما را تعیین کند و به شما این امکان را میدهد که از اعتبار حساب سرویس هنگام آزمایش یا اجرا در محیطهای غیر Google استفاده کنید.
از اعتبارنامه ها برای برش توکن های دسترسی استفاده کنید
مگر اینکه از Admin SDK استفاده کنید، که مجوز را به طور خودکار مدیریت می کند، باید رمز دسترسی را برش داده و برای ارسال درخواست ها اضافه کنید.
برای بازیابی رمز دسترسی کوتاه مدت OAuth 2.0، از اعتبارنامه Firebase خود به همراه کتابخانه Google Auth برای زبان دلخواه خود استفاده کنید:
در این مثال، کتابخانه سرویس گیرنده Google API درخواست را با یک توکن وب JSON یا JWT احراز هویت می کند. برای اطلاعات بیشتر، به نشانههای وب JSON مراجعه کنید.
پایتون
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
تاریخ آخرین بهروزرسانی 2025-09-03 بهوقت ساعت هماهنگ جهانی.
[[["درک آسان","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"]]