以程式設計方式設定 OAuth 身分提供者以進行 Firebase 驗證

您可以使用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) 配置,請將新組態發佈至projects.defaultSupportedIdpConfigs端點。

您需要指定身分提供者的 ID 以及您的用戶端 ID 和用戶端金鑰,這些資訊通常是從提供者的開發人員網站取得的。以下是 Firebase 支援的身份提供者及其 ID:

提供者識別碼
蘋果apple.com
蘋果遊戲中心gc.apple.com
Facebook facebook.com
GitHub github.com
Google google.com
谷歌玩遊戲playgames.google.com
領英linkedin.com
微軟microsoft.com
推特twitter.com
雅虎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 請求來取得提供者的目前配置。然後,對組態進行所需的更改,並將新組態修補到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。相反,請依照上一節中所示配置新的身分提供者。