הגדר באופן פרוגרמטי ספקי זהות OAuth עבור אימות Firebase

אתה יכול להשתמש ב- Google Cloud Identity Platform REST API כדי לנהל באופן פרוגרמטי את תצורת ספק הזהות של OAuth (IdP) של פרויקט Firebase. עם 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 .

יהיה עליך לציין את המזהה של ספק הזהות ואת מזהה הלקוח וסוד הלקוח שלך, שבדרך כלל אתה מקבל מאתר המפתחים של הספק. להלן ספקי הזהות שבהם Firebase תומך והמזהים שלהם:

ספק מזהה IdP
תפוח עץ apple.com
מרכז המשחקים של אפל gc.apple.com
פייסבוק facebook.com
GitHub github.com
גוגל google.com
Google Play משחקים 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, או לעדכן את תצורת הלקוח של הפרויקט שלך, קבל תחילה את התצורה הנוכחית של הספק על ידי ביצוע בקשת GET לנקודת הקצה projects.defaultSupportedIdpConfigs . לאחר מכן, בצע את השינויים שאתה רוצה בתצורה ותקן את התצורה החדשה לנקודת הקצה 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. במקום זאת, הגדר ספק זהות חדש כפי שמוצג בסעיף הקודם .