Configurare a livello di codice i provider di identità OAuth per l'autenticazione Firebase

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

Ottieni l'autorizzazione

Prima di poter chiamare l'API REST, è necessario un token di accesso OAuth 2.0 che conceda l'accesso Editor al tuo 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);
}

Aggiungi una nuova configurazione del provider di identità OAuth

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

Dovrai specificare l'ID del provider di identità, l'ID client e il segreto client, che in genere ottieni dal sito degli sviluppatori del provider. Ecco i provider di identità supportati da Firebase e i relativi ID:

Fornitore ID dell'IdP
Mela apple.com
Centro giochi Apple gc.apple.com
Facebook facebook.com
GitHub github.com
Google google.com
Giochi di Google Play 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. Per 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 invece 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 tuo progetto, ottieni innanzitutto la configurazione corrente del provider effettuando una richiesta GET all'endpoint projects.defaultSupportedIdpConfigs . Quindi, apporta le modifiche desiderate alla configurazione e applica la 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. Configura invece un nuovo provider di identità come mostrato nella sezione precedente .