透過程式為 Firebase 驗證設定 OAuth 識別資訊提供者

您可以使用 Google Cloud Identity Platform REST API,以程式輔助方式管理 Firebase 專案的 OAuth 識別資訊提供者 (IdP) 設定。您可以使用這個 API 設定要支援的識別資訊提供者,以及更新、啟用和停用專案目前的 OAuth 設定。

取得授權作業

呼叫 REST API 前,您需要取得 OAuth 2.0 存取權杖,授予 Firebase 專案的編輯者權限。舉例來說,如要在 Node.js 中使用服務帳戶取得存取權杖,請執行下列操作:

const googleAuth = require('google-auth-library');
const SCOPES = ['https://www.googleapis.com/auth/cloud-platform'];

async function getAccessToken() {
    const serviceAccount = require('/path/to/service_account_key.json');
    const jwtClient = new googleAuth.JWT(
        serviceAccount.client_email,
        null,
        serviceAccount.private_key,
        SCOPES,
        null
    );
    return jwtClient.authorize().then((tokens) => tokens.access_token);
}

新增 OAuth 識別資訊提供者設定

如要新增 OAuth 識別資訊提供者 (IdP) 設定,請將新設定 POST 至 projects.defaultSupportedIdpConfigs 端點。

您必須指定識別資訊提供者的 ID、用戶端 ID 和用戶端密鑰,這些資訊通常可從提供者的開發人員網站取得。以下是 Firebase 支援的識別資訊提供者及其 ID:

提供者 IdP ID
Apple apple.com
Apple Game Center gc.apple.com
Facebook facebook.com
GitHub github.com
Google google.com
Google Play 遊戲 playgames.google.com
LinkedIn linkedin.com
Microsoft microsoft.com
Twitter twitter.com
Yahoo yahoo.com

例如,使用 Node.js:

const fetch = require('node-fetch');
const GCIP_API_BASE = 'https://identitytoolkit.googleapis.com/v2';

async function addIdpConfig(projectId, accessToken, idpId, clientId, clientSecret) {
    const uri = `${GCIP_API_BASE}/projects/${projectId}/defaultSupportedIdpConfigs?idpId=${idpId}`;
    const options = {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${accessToken}`
        },
        body: JSON.stringify({
            name: `projects/${projectId}/defaultSupportedIdpConfigs/${idpId}`,
            enabled: true,
            clientId: clientId,
            clientSecret: clientSecret,
        }),
    };
    return fetch(uri, options).then((response) => {
        if (response.ok) {
            return response.json();
        } else if (response.status == 409) {
            throw new Error('IdP configuration already exists. Update it instead.');
        } else {
            throw new Error('Server error.');
        }
    });
}

(async () => {
    const projectId = 'your-firebase-project-id';
    const accessToken = await getAccessToken();
    const idpId = 'facebook.com';
    const clientId = 'your-facebook-client-id';
    const clientSecret = 'your-facebook-client-secret';
    try {
        await addIdpConfig(projectId, accessToken, idpId, clientId, clientSecret);
    } catch (err) {
        console.error(err.message);
    }
})().catch(console.error);

如果呼叫成功,就會傳回新建立的設定。例如:

{
  name: 'projects/your-numerical-project-id/defaultSupportedIdpConfigs/facebook.com',
  enabled: true,
  clientId: 'your-facebook-client-id',
  clientSecret: 'your-facebook-client-secret'
}

如果您嘗試設定已為專案設定的識別資訊提供者,呼叫會傳回 HTTP 錯誤 409。在這種情況下,您可以改為更新設定,如下所示。

更新 OAuth 識別資訊提供者設定

如要啟用或停用 OAuth 識別資訊提供者,或更新專案的用戶端設定,請先向 projects.defaultSupportedIdpConfigs 端點發出 GET 要求,取得提供者目前的設定。接著,對設定進行所需變更,並將新設定 PATCH 至 projects.defaultSupportedIdpConfigs 端點。

例如,使用 Node.js:

async function getIdpCfg(projectId, accessToken, idpId) {
    const uri = `${GCIP_API_BASE}/projects/${projectId}/defaultSupportedIdpConfigs/${idpId}`;
    const options = {
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${accessToken}`
        },
    };
    return fetch(uri, options).then((response) => {
        if (response.ok) {
            return response.json();
        } else if (response.status == 404) {
            throw new Error('IdP configuration not found. First add the IdP'
                            + ' configuration to your project.');
        } else {
            throw new Error('Server error.');
        }
    });
}

async function updateIdpConfig(accessToken, idpCfg) {
    const uri = `${GCIP_API_BASE}/${idpCfg.name}`;
    const options = {
        method: 'PATCH',
        headers: {
            'Authorization': `Bearer ${accessToken}`
        },
        body: JSON.stringify(idpCfg),
    };
    return fetch(uri, options).then((response) => {
        if (response.ok) {
            return response.json();
        } else if (response.status == 404) {
            throw new Error('IdP configuration not found. First add the IdP'
                            + ' configuration to your project.');
        } else {
            throw new Error('Server error.');
        }
    });
}

(async () => {
    const projectId = 'your-firebase-project-id';
    const accessToken = await getAccessToken();
    const idpId = 'facebook.com';
    try {
        // Get the IdP's current configuration.
        const idpCfg = await getIdpCfg(projectId, accessToken, idpId);

        // Update the configuration. (For example, disable the IdP.)
        idpCfg.enabled = false;
        await updateIdpConfig(accessToken, idpCfg);
    } catch (err) {
        console.error(err.message);
    }
})().catch(console.error);

如果您嘗試更新從未為專案設定的識別資訊提供者設定,呼叫會傳回 HTTP 錯誤 404。請改為按照上一節所述,設定新的識別資訊提供者。