Admin SDK는 권한 있는 환경에서 Firebase와 상호작용하여 다음과 같은 작업을 수행할 수 있게 해주는 서버 라이브러리 집합입니다.
- 전체 관리자 권한으로 실시간 데이터베이스 데이터를 읽고 씁니다.
- Firebase Cloud Messaging 서버 프로토콜에 대한 간단한 대체 접근 방식을 사용하여 프로그래밍 방식으로 Firebase Cloud Messaging 메시지를 보냅니다.
- Firebase 인증 토큰을 생성하고 확인합니다.
- Firebase 프로젝트와 연결된 Cloud Storage 버킷 및 Cloud Firestore 데이터베이스와 같은 Google Cloud 리소스에 액세스하세요.
- 사용자 데이터를 조회하거나 인증을 위해 사용자의 이메일 주소를 변경하는 등의 작업을 수행하기 위해 간소화된 관리 콘솔을 직접 만드세요.
권한 있는 환경(예: 서버)에서 관리자 액세스가 아닌 최종 사용자 액세스(예: Node.js 데스크톱 또는 IoT 애플리케이션)를 위한 클라이언트로 Node.js SDK를 사용하는 데 관심이 있는 경우 대신 클라이언트 JavaScript SDK 설정 지침을 따라야 합니다.
다음은 각 언어에서 지원되는 Firebase 기능을 보여주는 기능 매트릭스입니다.
이러한 용도의 Admin SDK 통합에 대해 자세히 알아보려면 해당하는 실시간 데이터베이스 , FCM , 인증 , 원격 구성 및 Cloud Storage 문서를 참조하세요. 이 페이지의 나머지 부분에서는 Admin SDK의 기본 설정에 중점을 둡니다.
전제 조건
서버 앱이 있는지 확인하십시오.
사용하는 Admin SDK에 따라 서버에서 다음을 실행하는지 확인하십시오.
- 관리 Node.js SDK — Node.js 14+
- 관리 자바 SDK — 자바 8+
- Admin Python SDK — Python 3.6 이상(Python 3.7 이상 권장)
- Admin Go SDK — Go 1.15+
- 관리 .NET SDK — .NET Framework 4.6.1+ 또는 .Net Core 2.0+용 .NET Standard 2.0
Firebase 프로젝트 및 서비스 계정 설정
Firebase Admin SDK를 사용하려면 다음이 필요합니다.
- Firebase 프로젝트.
- Firebase와 통신하기 위한 Firebase Admin SDK 서비스 계정. 이 서비스 계정은 Firebase 프로젝트를 만들거나 Google Cloud 프로젝트에 Firebase를 추가할 때 자동으로 생성됩니다.
- 서비스 계정의 사용자 인증 정보가 포함된 구성 파일.
아직 Firebase 프로젝트가 없다면 Firebase 콘솔 에서 프로젝트를 만들어야 합니다. Firebase 프로젝트에 대해 자세히 알아보려면 Firebase 프로젝트 이해 를 방문하세요.
SDK 추가
새 프로젝트를 설정하는 경우 선택한 언어에 대한 SDK를 설치해야 합니다.
Node.js
Firebase Admin Node.js SDK는 npm에서 사용할 수 있습니다. 아직 package.json
파일이 없다면 npm init
를 통해 파일을 만드세요. 다음으로 firebase-admin
npm 패키지를 설치하고 package.json
에 저장합니다.
npm install firebase-admin --save
애플리케이션에서 모듈을 사용하려면 모든 JavaScript 파일에서 모듈을 require
하십시오.
const { initializeApp } = require('firebase-admin/app');
ES2015를 사용하는 경우 모듈을 import
수 있습니다.
import { initializeApp } from 'firebase-admin/app';
자바
Firebase Admin Java SDK는 Maven 중앙 저장소에 게시됩니다. 라이브러리를 설치하려면 build.gradle
파일에서 라이브러리를 종속 항목으로 선언하세요.
dependencies {
implementation 'com.google.firebase:firebase-admin:9.1.1'
}
Maven을 사용하여 애플리케이션을 빌드하는 경우 pom.xml
에 다음 종속성을 추가할 수 있습니다.
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>9.1.1</version>
</dependency>
파이썬
Firebase Admin Python SDK는 pip 를 통해 사용할 수 있습니다. sudo
를 통해 모든 사용자를 위해 라이브러리를 설치할 수 있습니다.
sudo pip install firebase-admin
또는 --user
플래그를 전달하여 현재 사용자에 대해서만 라이브러리를 설치할 수 있습니다.
pip install --user firebase-admin
가다
Go Admin SDK는 go get
유틸리티를 사용하여 설치할 수 있습니다.
# Install as a module dependency
go get firebase.google.com/go/v4
# Install to $GOPATH
go get firebase.google.com/go
씨#
.NET Admin SDK는 .NET 패키지 관리자를 사용하여 설치할 수 있습니다.
Install-Package FirebaseAdmin -Version 2.3.0
또는 dotnet
명령줄 유틸리티를 사용하여 설치합니다.
dotnet add package FirebaseAdmin --version 2.3.0
또는 다음 패키지 참조 항목을 .csproj
파일에 추가하여 설치할 수 있습니다.
<ItemGroup>
<PackageReference Include="FirebaseAdmin" Version="2.3.0" />
</ItemGroup>
SDK 초기화
Firebase 프로젝트를 만든 후에는 Google 애플리케이션 기본 자격 증명 으로 SDK를 초기화할 수 있습니다. Google 환경에서는 기본 자격 증명 조회가 완전히 자동화되어 환경 변수나 기타 구성을 제공할 필요가 없기 때문에 Cloud Run, App Engine 및 Cloud Functions와 같은 Google 환경에서 실행되는 애플리케이션에는 SDK를 초기화하는 이 방법을 적극 권장합니다.
실시간 데이터베이스, Cloud Storage 또는 Cloud Functions와 같은 서비스의 초기화 옵션을 선택적으로 지정하려면 FIREBASE_CONFIG
환경 변수를 사용합니다. FIREBASE_CONFIG
변수의 내용이 {
로 시작하면 JSON 개체로 구문 분석됩니다. 그렇지 않으면 SDK는 문자열이 옵션을 포함하는 JSON 파일의 경로라고 가정합니다.
Node.js
const app = initializeApp();
자바
FirebaseApp.initializeApp();
파이썬
default_app = firebase_admin.initialize_app()
가다
app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
씨#
FirebaseApp.Create();
초기화되면 Admin SDK를 사용하여 다음 유형의 작업을 수행할 수 있습니다.
OAuth 2.0 갱신 토큰 사용
Admin SDK는 Google OAuth2 갱신 토큰으로 인증할 수 있는 자격 증명도 제공합니다.
Node.js
const myRefreshToken = '...'; // Get refresh token from OAuth2 flow
initializeApp({
credential: refreshToken(myRefreshToken),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});
자바
FileInputStream refreshToken = new FileInputStream("path/to/refreshToken.json");
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(refreshToken))
.setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
.build();
FirebaseApp.initializeApp(options);
파이썬
cred = credentials.RefreshToken('path/to/refreshToken.json')
default_app = firebase_admin.initialize_app(cred)
가다
opt := option.WithCredentialsFile("path/to/refreshToken.json")
config := &firebase.Config{ProjectID: "my-project-id"}
app, err := firebase.NewApp(context.Background(), config, opt)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
씨#
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("path/to/refreshToken.json"),
});
Google 이외의 환경에서 SDK 초기화
기본 사용자 인증 정보 조회를 완전히 자동화할 수 없는 Google 이외의 서버 환경에서 작업하는 경우 내보낸 서비스 계정 키 파일로 SDK를 초기화할 수 있습니다.
Firebase 프로젝트는 앱 서버 또는 신뢰할 수 있는 환경에서 Firebase 서버 API를 호출하는 데 사용할 수 있는 Google 서비스 계정 을 지원합니다. 로컬에서 코드를 개발하거나 애플리케이션을 온프레미스에 배포하는 경우 이 서비스 계정을 통해 얻은 자격 증명을 사용하여 서버 요청에 권한을 부여할 수 있습니다.
서비스 계정을 인증하고 Firebase 서비스에 액세스할 수 있는 권한을 부여하려면 JSON 형식의 비공개 키 파일을 생성해야 합니다.
서비스 계정의 비공개 키 파일을 생성하려면 다음 안내를 따르세요.
Firebase 콘솔에서 설정 > 서비스 계정 을 엽니다.
새 개인 키 생성 을 클릭한 다음 키 생성 을 클릭하여 확인합니다.
키가 포함된 JSON 파일을 안전하게 저장합니다.
서비스 계정을 통해 승인할 때 애플리케이션에 자격 증명을 제공하기 위한 두 가지 선택 사항이 있습니다. GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 설정하거나 코드에서 서비스 계정 키의 경로를 명시적으로 전달할 수 있습니다. 첫 번째 옵션은 더 안전하며 강력하게 권장됩니다.
환경 변수를 설정하려면:
환경 변수 GOOGLE_APPLICATION_CREDENTIALS 를 서비스 계정 키가 포함된 JSON 파일의 파일 경로로 설정합니다. 이 변수는 현재 셸 세션에만 적용되므로 새 세션을 열 경우 변수를 다시 설정하십시오.
리눅스 또는 macOS
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"
윈도우
PowerShell 사용:
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"
위의 단계를 완료하면 애플리케이션 기본 사용자 인증 정보(ADC)가 암시적으로 사용자 인증 정보를 결정할 수 있으므로 Google 이외의 환경에서 테스트하거나 실행할 때 서비스 계정 사용자 인증 정보를 사용할 수 있습니다.
다음과 같이 SDK를 초기화합니다.
Node.js
initializeApp({
credential: applicationDefault(),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});
자바
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.getApplicationDefault())
.setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
.build();
FirebaseApp.initializeApp(options);
파이썬
default_app = firebase_admin.initialize_app()
가다
app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
씨#
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.GetApplicationDefault(),
});
여러 앱 초기화
대부분의 경우 하나의 기본 앱만 초기화하면 됩니다. 두 가지 동등한 방법으로 해당 앱에서 서비스에 액세스할 수 있습니다.
Node.js
// Initialize the default app
const defaultApp = initializeApp(defaultAppConfig);
console.log(defaultApp.name); // '[DEFAULT]'
// Retrieve services via the defaultApp variable...
let defaultAuth = getAuth(defaultApp);
let defaultDatabase = getDatabase(defaultApp);
// ... or use the equivalent shorthand notation
defaultAuth = getAuth();
defaultDatabase = getDatabase();
자바
// Initialize the default app
FirebaseApp defaultApp = FirebaseApp.initializeApp(defaultOptions);
System.out.println(defaultApp.getName()); // "[DEFAULT]"
// Retrieve services by passing the defaultApp variable...
FirebaseAuth defaultAuth = FirebaseAuth.getInstance(defaultApp);
FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance(defaultApp);
// ... or use the equivalent shorthand notation
defaultAuth = FirebaseAuth.getInstance();
defaultDatabase = FirebaseDatabase.getInstance();
파이썬
# Import the Firebase service
from firebase_admin import auth
# Initialize the default app
default_app = firebase_admin.initialize_app(cred)
print(default_app.name) # "[DEFAULT]"
# Retrieve services via the auth package...
# auth.create_custom_token(...)
가다
// Initialize default app
app, err := firebase.NewApp(context.Background(), nil)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
// Access auth service from the default app
client, err := app.Auth(context.Background())
if err != nil {
log.Fatalf("error getting Auth client: %v\n", err)
}
씨#
// Initialize the default app
var defaultApp = FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.GetApplicationDefault(),
});
Console.WriteLine(defaultApp.Name); // "[DEFAULT]"
// Retrieve services by passing the defaultApp variable...
var defaultAuth = FirebaseAuth.GetAuth(defaultApp);
// ... or use the equivalent shorthand notation
defaultAuth = FirebaseAuth.DefaultInstance;
일부 사용 사례에서는 동시에 여러 앱을 생성해야 합니다. 예를 들어 한 Firebase 프로젝트의 실시간 데이터베이스에서 데이터를 읽고 다른 프로젝트의 맞춤 토큰을 만들 수 있습니다. 또는 별도의 자격 증명으로 두 개의 앱을 인증할 수 있습니다. Firebase SDK를 사용하면 각각 자체 구성 정보가 있는 여러 앱을 동시에 만들 수 있습니다.
Node.js
// Initialize the default app
initializeApp(defaultAppConfig);
// Initialize another app with a different config
var otherApp = initializeApp(otherAppConfig, 'other');
console.log(getApp().name); // '[DEFAULT]'
console.log(otherApp.name); // 'other'
// Use the shorthand notation to retrieve the default app's services
const defaultAuth = getAuth();
const defaultDatabase = getDatabase();
// Use the otherApp variable to retrieve the other app's services
const otherAuth = getAuth(otherApp);
const otherDatabase = getDatabase(otherApp);
자바
// Initialize the default app
FirebaseApp defaultApp = FirebaseApp.initializeApp(defaultOptions);
// Initialize another app with a different config
FirebaseApp otherApp = FirebaseApp.initializeApp(otherAppConfig, "other");
System.out.println(defaultApp.getName()); // "[DEFAULT]"
System.out.println(otherApp.getName()); // "other"
// Use the shorthand notation to retrieve the default app's services
FirebaseAuth defaultAuth = FirebaseAuth.getInstance();
FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance();
// Use the otherApp variable to retrieve the other app's services
FirebaseAuth otherAuth = FirebaseAuth.getInstance(otherApp);
FirebaseDatabase otherDatabase = FirebaseDatabase.getInstance(otherApp);
파이썬
# Initialize the default app
default_app = firebase_admin.initialize_app(cred)
# Initialize another app with a different config
other_app = firebase_admin.initialize_app(cred, name='other')
print(default_app.name) # "[DEFAULT]"
print(other_app.name) # "other"
# Retrieve default services via the auth package...
# auth.create_custom_token(...)
# Use the `app` argument to retrieve the other app's services
# auth.create_custom_token(..., app=other_app)
가다
// Initialize the default app
defaultApp, err := firebase.NewApp(context.Background(), nil)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
// Initialize another app with a different config
opt := option.WithCredentialsFile("service-account-other.json")
otherApp, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
// Access Auth service from default app
defaultClient, err := defaultApp.Auth(context.Background())
if err != nil {
log.Fatalf("error getting Auth client: %v\n", err)
}
// Access auth service from other app
otherClient, err := otherApp.Auth(context.Background())
if err != nil {
log.Fatalf("error getting Auth client: %v\n", err)
}
씨#
// Initialize the default app
var defaultApp = FirebaseApp.Create(defaultOptions);
// Initialize another app with a different config
var otherApp = FirebaseApp.Create(otherAppConfig, "other");
Console.WriteLine(defaultApp.Name); // "[DEFAULT]"
Console.WriteLine(otherApp.Name); // "other"
// Use the shorthand notation to retrieve the default app's services
var defaultAuth = FirebaseAuth.DefaultInstance;
// Use the otherApp variable to retrieve the other app's services
var otherAuth = FirebaseAuth.GetAuth(otherApp);
실시간 데이터베이스 및 인증 범위 설정
실시간 데이터베이스 또는 인증을 위해 Google 애플리케이션 기본 사용자 인증 정보와 함께 Google Compute Engine VM을 사용하는 경우 올바른 액세스 범위 도 설정해야 합니다. 실시간 데이터베이스 및 인증의 경우 userinfo.email
및 cloud-platform
또는 firebase.database
로 끝나는 범위가 필요합니다. 기존 액세스 범위를 확인하고 변경하려면 gcloud 를 사용하여 다음 명령어를 실행합니다.
gcloud
# Check the existing access scopes
gcloud compute instances describe [INSTANCE_NAME] --format json
# The above command returns the service account information. For example:
"serviceAccounts": [
{
"email": "your.gserviceaccount.com",
"scopes": [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/userinfo.email"
]
}
],
# Stop the VM, then run the following command, using the service account
# that gcloud returned when you checked the scopes.
gcloud compute instances set-service-account [INSTANCE_NAME] --service-account "your.gserviceaccount.com" --scopes "https://www.googleapis.com/auth/firebase.database,https://www.googleapis.com/auth/userinfo.email"
gcloud 최종 사용자 인증 정보로 테스트
gcloud auth application-default login
을 실행하여 얻은 Google 애플리케이션 기본 사용자 인증 정보로 Admin SDK를 로컬에서 테스트할 때 Firebase 인증을 사용하려면 다음과 같은 이유로 추가 변경이 필요합니다.
- Firebase 인증은 gcloud OAuth 클라이언트 ID를 사용하여 생성된 gcloud 최종 사용자 인증 정보를 허용하지 않습니다.
- Firebase 인증을 사용하려면 이러한 유형의 최종 사용자 자격 증명을 초기화할 때 프로젝트 ID를 제공해야 합니다.
해결 방법으로 자체 OAuth 2.0 클라이언트 ID 를 사용하여 gcloud 에서 Google 애플리케이션 기본 사용자 인증 정보를 생성할 수 있습니다. OAuth 클라이언트 ID는 데스크톱 앱 애플리케이션 유형이어야 합니다.
gcloud
gcloud auth application-default login --client-id-file=[/path/to/client/id/file]
앱 초기화 시 명시적으로 프로젝트 ID를 지정하거나 GOOGLE_CLOUD_PROJECT
환경 변수를 사용할 수 있습니다. 후자는 코드를 테스트하기 위해 추가로 변경할 필요가 없습니다.
프로젝트 ID를 명시적으로 지정하려면 다음 안내를 따르세요.
Node.js
import { initializeApp, applicationDefault } from 'firebase-admin/app';
initializeApp({
credential: applicationDefault(),
projectId: '<FIREBASE_PROJECT_ID>',
});
자바
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.getApplicationDefault())
.setProjectId("<FIREBASE_PROJECT_ID>")
.build();
FirebaseApp.initializeApp(options);
파이썬
app_options = {'projectId': '<FIREBASE_PROJECT_ID>'}
default_app = firebase_admin.initialize_app(options=app_options)
가다
config := &firebase.Config{ProjectID: "<FIREBASE_PROJECT_ID>"}
app, err := firebase.NewApp(context.Background(), config)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
씨#
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.GetApplicationDefault(),
ProjectId = "<FIREBASE_PROJECT_ID>",
});
다음 단계
Firebase에 대해 알아보기:
샘플 Firebase 앱 을 살펴보세요.
Admin SDK 작성자 중 한 명이 작성한 Admin SDK 관련 블로그 게시물 을 읽어보세요. 예: 프록시 서버를 통해 Firestore 및 Firebase에 액세스 .
앱에 Firebase 기능을 추가합니다.
- Cloud Functions 로 서버리스 백엔드를 작성합니다.
- 실시간 데이터베이스 에 정보를 저장하거나 Cloud Storage 에 blob 데이터를 저장합니다.
- 클라우드 메시징 으로 알림을 받습니다.