Configurare in modo programmatico i provider di identità OAuth per Firebase Authentication

Puoi utilizzare l'API REST Google Cloud Identity Platform per gestire a livello di programmazione il provider di identità OAuth (IdP) di un progetto Firebase configurazione. Con questa API puoi configurare i provider di identità desiderati per supportare e aggiornare, abilitare e disabilitare la funzionalità OAuth attuale del progetto configurazioni.

Recupera autorizzazione

Prima di poter chiamare l'API REST, devi avere un token di accesso OAuth 2.0 che conceda Accesso in modifica al progetto Firebase. Ad esempio, per ottenere un token di accesso utilizzando un account di servizio 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);
}

Aggiungere una nuova configurazione del provider di identità OAuth

Per aggiungere una nuova configurazione del provider di identità (IdP) OAuth, POSTA la nuova configurazione configurazione in projects.defaultSupportedIdpConfigs endpoint.

Dovrai specificare l'ID del provider di identità, il tuo ID client e client secret, che in genere si ottiene dal sito per sviluppatori del provider. Di seguito sono riportati i provider di identità supportati da Firebase e i relativi ID:

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

Ad esempio, utilizzando 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);

Se la chiamata va a buon fine, restituisce la configurazione appena creata. Ad esempio:

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

Se provi a configurare un provider di identità già configurato per il tuo progetto, la chiamata restituisce l'errore HTTP 409. In questo caso, puoi aggiornare la configurazione, come descritto di seguito.

Aggiorna la configurazione di un provider di identità OAuth

Per attivare o disattivare un provider di identità OAuth o aggiornare la configurazione del client del progetto, ottieni prima la configurazione corrente del provider inviando una richiesta GET all'endpoint projects.defaultSupportedIdpConfigs. Poi, apporta le modifiche necessarie alla configurazione e applica il patch alla nuova configurazione nell'endpoint projects.defaultSupportedIdpConfigs.

Ad esempio, utilizzando 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);

Se provi ad aggiornare la configurazione di un provider di identità che non hai mai configurato per il tuo progetto, le chiamate restituiranno l'errore HTTP 404. Invece, configurare un nuovo provider di identità come mostrato nella precedente .