إعداد موفِّري هوية OAuth آليًا لمصادقة Firebase

يمكنك استخدام واجهة برمجة تطبيقات REST في Google Cloud Identity Platform من أجل الإدارة الآلية لموفّر هوية OAuth لمشروع Firebase التكوين. باستخدام واجهة برمجة التطبيقات هذه، يمكنك ضبط إعدادات موفِّري الهوية الذين تريدهم لدعم بروتوكول OAuth الحالي لمشروعك وتحديثه وتفعيله وإيقافه الإعدادات.

الحصول على تفويض

قبل طلب واجهة برمجة تطبيقات 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، يمكنك نشر النسخة الجديدة الإعداد إلى projects.defaultSupportedIdpConfigs النهائية.

ستحتاج إلى تحديد معرّف موفِّر الهوية ومعرِّف العميل بسر العميل، والذي تحصل عليه عادةً من موقع مطور مقدم الخدمة. هنا موفرو الهوية الذين يدعمهم Firebase وأرقام تعريفهم:

المزوّد رقم تعريف موفِّر الهوية
Apple apple.com
مركز ألعاب Apple gc.apple.com
Facebook facebook.com
GitHub github.com
Google google.com
ألعاب Google Play 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. بعد ذلك، يمكنك إجراء التغييرات التي تريدها على الإعدادات وتصحيح الإعداد إلى 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. بدلاً من ذلك، إعداد موفِّر هوية جديد كما هو موضَّح في المقالة السابقة .