Firebase SDK は、ユーザーに代わって Firebase Realtime Database とのすべての認証と通信を処理します。ただし、クライアント SDK がない環境にいる場合、または永続的なデータベース接続のオーバーヘッドを回避したい場合は、Realtime Database REST API を使用してデータの読み取りと書き込みを行うことができます。
次のいずれかの方法でユーザーを認証します。
Google OAuth2 アクセス トークン- 通常、Realtime Database に対する読み取りと書き込みの機能は、 Realtime Database ルールによって管理されます。ただし、サーバーからデータにアクセスし、サービス アカウントから生成された Google OAuth2 アクセス トークンを使用して、そのサーバーにデータへの完全な読み取りおよび書き込みアクセスを許可することができます。
Firebase ID トークン- クライアント SDK の Realtime Database ルールでアクセスを制限するなど、個々のユーザーとして認証されたリクエストを送信することもできます。 REST API は、クライアント SDK で使用されるものと同じ Firebase ID トークンを受け入れます。
Google OAuth2 アクセス トークン
Realtime Database ルールに従ってパブリックに読み取りまたは書き込み可能なデータは、認証なしで REST API 経由でも読み取りおよび書き込みが可能です。ただし、サーバーに Realtime Database ルールをバイパスさせたい場合は、読み取りおよび書き込みリクエストを認証する必要があります。 Google OAuth2 による認証には、次の手順が必要です。
- アクセス トークンを生成します。
- そのアクセス トークンで認証します。
アクセス トークンを生成する
Realtime Database REST API は、標準のGoogle OAuth2 アクセス トークンを受け入れます。アクセス トークンは、Realtime Database に対する適切な権限を持つサービス アカウントを使用して生成できます。 Firebase コンソールの [ Service Accounts]セクションの下部にある [ Generate New Private Key ] ボタンをクリックすると、新しいサービス アカウント キー ファイルをまだ持っていない場合に簡単に生成できます。
サービス アカウント キー ファイルを取得したら、 Google API クライアント ライブラリのいずれかを使用して、次の必要なスコープを持つ Google OAuth2 アクセス トークンを生成できます。
-
https://www.googleapis.com/auth/userinfo.email
-
https://www.googleapis.com/auth/firebase.database
さまざまな言語で Realtime Database REST API に対して認証するための Google OAuth2 アクセス トークンを作成する方法を示す実装例を次に示します。
Node.js
Node.js 用 Google API クライアント ライブラリの使用:
var {google} = require("googleapis");
// Load the service account key JSON file.
var serviceAccount = require("path/to/serviceAccountKey.json");
// Define the required scopes.
var scopes = [
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/firebase.database"
];
// Authenticate a JWT client with the service account.
var jwtClient = new google.auth.JWT(
serviceAccount.client_email,
null,
serviceAccount.private_key,
scopes
);
// Use the JWT client to generate an access token.
jwtClient.authorize(function(error, tokens) {
if (error) {
console.log("Error making request to generate access token:", error);
} else if (tokens.access_token === null) {
console.log("Provided service account does not have permission to generate access tokens");
} else {
var accessToken = tokens.access_token;
// See the "Using the access token" section below for information
// on how to use the access token to send authenticated requests to
// the Realtime Database REST API.
}
});
ジャワ
Java 用 Google API クライアント ライブラリの使用:
// Load the service account key JSON file
FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");
// Authenticate a Google credential with the service account
GoogleCredential googleCred = GoogleCredential.fromStream(serviceAccount);
// Add the required scopes to the Google credential
GoogleCredential scoped = googleCred.createScoped(
Arrays.asList(
"https://www.googleapis.com/auth/firebase.database",
"https://www.googleapis.com/auth/userinfo.email"
)
);
// Use the Google credential to generate an access token
scoped.refreshToken();
String token = scoped.getAccessToken();
// See the "Using the access token" section below for information
// on how to use the access token to send authenticated requests to the
// Realtime Database REST API.
パイソン
google-auth
ライブラリの使用:
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
# Define the required scopes
scopes = [
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/firebase.database"
]
# Authenticate a credential with the service account
credentials = service_account.Credentials.from_service_account_file(
"path/to/serviceAccountKey.json", scopes=scopes)
# Use the credentials object to authenticate a Requests session.
authed_session = AuthorizedSession(credentials)
response = authed_session.get(
"https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json")
# Or, use the token directly, as described in the "Authenticate with an
# access token" section below. (not recommended)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
access_token = credentials.token
アクセストークンで認証する
認証済みのリクエストを Realtime Database REST API に送信するには、上記で生成した Google OAuth2 アクセス トークンをAuthorization: Bearer <ACCESS_TOKEN>
ヘッダーまたはaccess_token=<ACCESS_TOKEN>
クエリ文字列パラメーターとして渡します。 Ada の名前を読み取るためのcurl
リクエストの例を次に示します。
curl "https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json?access_token=<ACCESS_TOKEN>"
<DATABASE_NAME>
を Realtime Database の名前に、 <ACCESS_TOKEN>
を Google OAuth2 アクセス トークンに置き換えてください。
成功したリクエストは、 200 OK
HTTP ステータス コードによって示されます。応答には、取得されるデータが含まれています。
{"first":"Ada","last":"Lovelace"}
Firebase ID トークン
ユーザーまたはデバイスが Firebase Authentication を使用してサインインすると、Firebase はそれらを一意に識別する対応する ID トークンを作成し、Realtime Database や Cloud Storage などの複数のリソースへのアクセスを許可します。その ID トークンを再利用して Realtime Database REST API を認証し、そのユーザーに代わってリクエストを行うことができます。
ID トークンを生成する
クライアントから Firebase ID トークンを取得するには、クライアントで ID トークンを取得する の手順に従います。
ID トークンは短期間で期限切れになるため、取得後はできるだけ早く使用する必要があることに注意してください。
ID トークンで認証する
認証済みのリクエストを Realtime Database REST API に送信するには、上記で生成した ID トークンをauth=<ID_TOKEN>
クエリ文字列パラメーターとして渡します。 Ada の名前を読み取るためのcurl
リクエストの例を次に示します。
curl "https://<DATABASE_NAME>.firebaseio.com/users/ada/name.json?auth=<ID_TOKEN>"
<DATABASE_NAME>
を Realtime Database の名前に、 <ID_TOKEN>
を Firebase ID トークンに置き換えてください。
成功したリクエストは、 200 OK
HTTP ステータス コードによって示されます。応答には、取得されるデータが含まれています。
{"first":"Ada","last":"Lovelace"}
レガシートークン
従来の Firebase 認証トークンをまだ使用している場合は、REST 認証を上記のいずれかの認証方法に更新することをお勧めします。
Realtime Database REST API は、シークレットを含む従来の認証トークンによる認証を引き続きサポートします。 Realtime Database シークレットは、Firebase コンソールの [サービス アカウント]セクションにあります。