Định cấu hình theo chương trình nhà cung cấp danh tính OAuth cho Xác thực Firebase

Bạn có thể sử dụng API REST của Google Cloud Identity Platform để quản lý theo chương trình cấu hình nhà cung cấp danh tính OAuth (IdP) của dự án Firebase. Với API này, bạn có thể định cấu hình nhà cung cấp danh tính mà bạn muốn hỗ trợ cũng như cập nhật, bật và tắt cấu hình OAuth hiện tại cho dự án của bạn.

Nhận ủy quyền

Trước khi có thể gọi API REST, bạn cần có mã thông báo truy cập OAuth 2.0 để cấp cho Trình chỉnh sửa quyền truy cập vào dự án Firebase của bạn. Ví dụ: để nhận mã thông báo truy cập bằng tài khoản dịch vụ trong 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);
}

Thêm cấu hình nhà cung cấp danh tính OAuth mới

Để thêm cấu hình nhà cung cấp danh tính OAuth (IdP) mới, hãy ĐĂNG cấu hình mới tới điểm cuối của projects.defaultSupportedIdpConfigs .

Bạn sẽ cần chỉ định ID của nhà cung cấp danh tính cũng như ID khách hàng và bí mật khách hàng mà bạn thường lấy từ trang web dành cho nhà phát triển của nhà cung cấp. Dưới đây là các nhà cung cấp danh tính mà Firebase hỗ trợ và ID của họ:

Các nhà cung cấp Mã nhà cung cấp
Quả táo apple.com
Trung tâm trò chơi Apple gc.apple.com
Facebook facebook.com
GitHub github.com
Google google.com
Trò chơi trên Google Play playgames.google.com
LinkedIn linkedin.com
Microsoft microsoft.com
Twitter twitter.com
Yahoo yahoo.com

Ví dụ: sử dụng 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);

Nếu cuộc gọi thành công, nó sẽ trả về cấu hình mới được tạo. Ví dụ:

{
  name: 'projects/your-numerical-project-id/defaultSupportedIdpConfigs/facebook.com',
  enabled: true,
  clientId: 'your-facebook-client-id',
  clientSecret: 'your-facebook-client-secret'
}

Nếu bạn cố gắng định cấu hình một nhà cung cấp danh tính đã được đặt cấu hình cho dự án của mình thì cuộc gọi sẽ trả về lỗi HTTP 409. Trong trường hợp này, bạn có thể cập nhật cấu hình thay thế như mô tả bên dưới.

Cập nhật cấu hình nhà cung cấp danh tính OAuth

Để bật hoặc tắt nhà cung cấp danh tính OAuth hoặc cập nhật cấu hình máy khách cho dự án của bạn, trước tiên hãy lấy cấu hình hiện tại của nhà cung cấp bằng cách thực hiện yêu cầu GET tới điểm cuối của projects.defaultSupportedIdpConfigs . Sau đó, thực hiện các thay đổi bạn muốn đối với cấu hình và VÁ cấu hình mới vào điểm cuối projects.defaultSupportedIdpConfigs .

Ví dụ: sử dụng 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);

Nếu bạn cố cập nhật cấu hình của nhà cung cấp danh tính mà bạn chưa từng định cấu hình cho dự án của mình thì các lệnh gọi sẽ trả về lỗi HTTP 404. Thay vào đó, hãy định cấu hình nhà cung cấp danh tính mới như được hiển thị trong phần trước .