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

Puoi utilizzare l'API REST di Google Cloud Identity Platform per gestire in modo programmatico la configurazione del provider di identità (IdP) OAuth di un progetto Firebase. Con questa API puoi configurare i provider di identità che vuoi supportare e aggiornare, abilitare e disabilitare le configurazioni OAuth attuali del tuo progetto.

Recupera autorizzazione

Prima di poter chiamare l'API REST, devi disporre di un token di accesso OAuth 2.0 che conceda l'accesso come editor al tuo progetto Firebase. Ad esempio, per ottenere un token di accesso utilizzando un service account 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);
}

Aggiungi una nuova configurazione del provider di identità OAuth

Per aggiungere una nuova configurazione del provider di identità (IdP) OAuth, invia la nuova configurazione tramite POST all'endpoint projects.defaultSupportedIdpConfigs.

Dovrai specificare l'ID del provider di identità, l'ID client e il client secret, che in genere ottieni dal sito per sviluppatori del provider. Ecco 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 ha esito positivo, 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à che è già stato configurato per il tuo progetto, la chiamata restituisce l'errore HTTP 409. In questa situazione, puoi aggiornare la configurazione come descritto di seguito.

Aggiorna la configurazione di un provider di identità OAuth

Per abilitare o disabilitare un provider di identità OAuth o aggiornare la configurazione del client del progetto, recupera prima la configurazione attuale del provider inviando una richiesta GET all'endpoint projects.defaultSupportedIdpConfigs. Quindi, apporta le modifiche che vuoi alla configurazione e applica PATCH alla nuova configurazione all'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, configura un nuovo provider di identità come mostrato nella sezione precedente.