서버 환경의 세부정보에 따라 다음 전략을 조합하여 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는 사용자 인증 정보를 암묵적으로 찾을 수 있습니다.
Firebase 프로젝트는 앱 서버 또는 신뢰할 수 있는 환경에서 Firebase Server API를 호출하는 데 사용할 수 있는 Google 서비스 계정을 지원합니다. 로컬에서 코드를 개발하거나 온프레미스에 애플리케이션을 배포하는 경우 이 서비스 계정을 통해 가져온 사용자 인증 정보를 사용하여 서버 요청을 승인할 수 있습니다.
서비스 계정을 인증하고 Firebase 서비스에 액세스하도록 승인하려면 JSON 형식의 비공개 키 파일을 생성해야 합니다.
서비스 계정을 통한 승인 시 다음과 같은 2가지 방법을 사용하여 애플리케이션에 사용자 인증 정보를 제공할 수 있습니다. GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 설정하거나 코드에서 서비스 계정 키 경로를 명시적으로 전달하는 것입니다.
그러나 보안을 위해 첫 번째 방법을 강력하게 권장합니다.
환경 변수를 설정하는 방법은 다음과 같습니다.
GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 서비스 계정 키가 포함된 JSON 파일의 파일 경로로 설정합니다.
이 변수는 현재 셸 세션에만 적용되므로 새 세션을 열면 변수를 다시 설정합니다.
이 예시는 Google API 클라이언트 라이브러리에서 JSON 웹 토큰(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-04(UTC)"],[],[],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"]]