הגדרה פרוגרמטית של ספקי זהויות של OAuth לצורך אימות ב-Firebase

אתם יכולים להשתמש ב-Google Cloud Identity Platform REST API כדי לנהל באופן פרוגרמטי את ההגדרות של ספק הזהויות (IdP) ב-OAuth של פרויקט Firebase. באמצעות ה-API הזה, אתם יכולים להגדיר את ספקי הזהויות שאתם רוצים לתמוך בהם, ולעדכן, להפעיל ולהשבית את הגדרות ה-OAuth הנוכחיות של הפרויקט.

קבלת הרשאה

כדי לשלוח קריאה ל-API בארכיטקטורת REST, צריך אסימון גישה מסוג 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

כדי להוסיף הגדרה חדשה של ספק זהויות (IdP) ב-OAuth, שולחים בקשת POST של ההגדרה החדשה לנקודת הקצה projects.defaultSupportedIdpConfigs.

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

ספק מזהה IdP
Apple apple.com
Apple Game Center gc.apple.com
Facebook facebook.com
GitHub github.com
Google google.com
Google Play Games playgames.google.com
LinkedIn linkedin.com
Microsoft microsoft.com
Twitter twitter.com
Yahoo 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. לאחר מכן, מבצעים את השינויים הרצויים בהגדרות ומשתמשים ב-PATCH כדי להחיל את ההגדרות החדשות בנקודת הקצה 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. במקום זאת, צריך להגדיר ספק זהויות חדש, כמו שמתואר בקטע הקודם.