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

您可以使用 Google Cloud Identity Platform REST API 執行下列操作: 以程式輔助方式管理 Firebase 專案的 OAuth 識別資訊提供者 (IdP) 此外還會從 0 自動調整資源配置 您完全不必調整資源調度設定您可以透過這個 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 識別資訊提供者,或更新專案的用戶端 請先建立 GET 要求傳送至 projects.defaultSupportedIdpConfigs 端點。 然後進行所需設定變更,並 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 設定新的識別資訊提供者,如先前所述 專區