Konfigurieren Sie OAuth-Identitätsanbieter programmgesteuert für die Firebase-Authentifizierung

Sie können die REST-API der Google Cloud Identity Platform verwenden, um die OAuth-Identitätsanbieterkonfiguration (IdP) eines Firebase-Projekts programmgesteuert zu verwalten. Mit dieser API können Sie die Identitätsanbieter konfigurieren, die Sie unterstützen möchten, und die aktuellen OAuth-Konfigurationen Ihres Projekts aktualisieren, aktivieren und deaktivieren.

Holen Sie sich eine Autorisierung

Bevor Sie die REST-API aufrufen können, benötigen Sie ein OAuth 2.0-Zugriffstoken, das Editorzugriff auf Ihr Firebase-Projekt gewährt. So erhalten Sie beispielsweise ein Zugriffstoken mithilfe eines Dienstkontos in 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);
}

Fügen Sie eine neue OAuth-Identitätsanbieterkonfiguration hinzu

Um eine neue OAuth-Identitätsanbieterkonfiguration (IdP) hinzuzufügen, posten Sie die neue Konfiguration an den Endpunkt projects.defaultSupportedIdpConfigs .

Sie müssen die ID des Identitätsanbieters sowie Ihre Client-ID und Ihr Client-Geheimnis angeben, die Sie normalerweise von der Entwicklerseite des Anbieters erhalten. Hier sind die von Firebase unterstützten Identitätsanbieter und ihre IDs:

Anbieter IdP-ID
Apfel apple.com
Apple Game Center gc.apple.com
Facebook facebook.com
GitHub github.com
Google google.com
Google Play-Spiele playgames.google.com
LinkedIn linkedin.com
Microsoft microsoft.com
Twitter twitter.com
Yahoo yahoo.com

Beispielsweise mit 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);

Wenn der Aufruf erfolgreich ist, wird die neu erstellte Konfiguration zurückgegeben. Zum Beispiel:

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

Wenn Sie versuchen, einen Identitätsanbieter zu konfigurieren, der bereits für Ihr Projekt konfiguriert wurde, gibt der Aufruf den HTTP-Fehler 409 zurück. In dieser Situation können Sie stattdessen die Konfiguration aktualisieren, wie unten beschrieben.

Aktualisieren Sie die Konfiguration eines OAuth-Identitätsanbieters

Um einen OAuth-Identitätsanbieter zu aktivieren oder zu deaktivieren oder die Clientkonfiguration Ihres Projekts zu aktualisieren, rufen Sie zunächst die aktuelle Konfiguration des Anbieters ab, indem Sie eine GET-Anfrage an den Endpunkt projects.defaultSupportedIdpConfigs stellen. Nehmen Sie dann die gewünschten Änderungen an der Konfiguration vor und patchen Sie die neue Konfiguration mit dem Endpunkt projects.defaultSupportedIdpConfigs .

Beispielsweise mit 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);

Wenn Sie versuchen, die Konfiguration eines Identitätsanbieters zu aktualisieren, den Sie noch nie für Ihr Projekt konfiguriert haben, geben die Aufrufe den HTTP-Fehler 404 zurück. Konfigurieren Sie stattdessen einen neuen Identitätsanbieter, wie im vorherigen Abschnitt gezeigt.