تكوين موفري هوية OAuth برمجيًا لمصادقة Firebase

يمكنك استخدام Google Cloud Identity Platform REST API لإدارة تهيئة موفر هوية OAuth (IdP) لمشروع Firebase برمجيًا. باستخدام واجهة برمجة التطبيقات هذه، يمكنك تكوين موفري الهوية الذين ترغب في دعمهم، وتحديث وتمكين وتعطيل تكوينات 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 ومعرفاتهم:

مزود معرف موفر الهوية
تفاحة apple.com
مركز ألعاب أبل gc.apple.com
فيسبوك facebook.com
جيثب github.com
جوجل google.com
العاب جوجل بلاي 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. وبدلاً من ذلك، قم بتكوين موفر هوية جديد كما هو موضح في القسم السابق .