Firebase Authentication için OAuth kimlik sağlayıcılarını program aracılığıyla yapılandırma

Bir Firebase projesinin OAuth kimlik sağlayıcısı (IdP) yapılandırmasını programlı bir şekilde yönetmek için Google Cloud Identity Platform REST API'yi kullanabilirsiniz. Bu API ile desteklemek istediğiniz kimlik sağlayıcılarını yapılandırabilir ve projenizin mevcut OAuth yapılandırmalarını güncelleyebilir, etkinleştirebilir ve devre dışı bırakabilirsiniz.

Yetki alın

REST API'yi çağırabilmeniz için Firebase projenize Düzenleyici erişimi sağlayan bir OAuth 2.0 erişim jetonuna ihtiyacınız vardır. Örneğin, Node.js'de bir hizmet hesabını kullanarak erişim belirteci almak için:

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);
}

Yeni bir OAuth kimlik sağlayıcısı yapılandırması ekleyin

Yeni bir OAuth kimlik sağlayıcısı (IdP) yapılandırması eklemek için yeni yapılandırmayı projects.defaultSupportedIdpConfigs uç noktasına POST yapın.

Kimlik sağlayıcının kimliğini ve genellikle sağlayıcının geliştirici sitesinden alacağınız müşteri kimliğinizi ve müşteri sırrınızı belirtmeniz gerekecektir. Firebase'in desteklediği kimlik sağlayıcıları ve kimlikleri şunlardır:

Sağlayıcı IdP kimliği
Elma apple.com
Apple Oyun Merkezi gc.apple.com
Facebook facebook.com
GitHub github.com
Google google.com
Google Play Oyunlar playgames.google.com
LinkedIn linkedin.com
Microsoft microsoft.com
heyecan twitter.com
yahoo yahoo.com

Örneğin, Node.js'yi kullanarak:

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);

Çağrı başarılı olursa yeni oluşturulan konfigürasyonu döndürür. Örneğin:

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

Projeniz için önceden yapılandırılmış bir kimlik sağlayıcıyı yapılandırmaya çalışırsanız çağrı, HTTP hatası 409'u döndürür. Bu durumda, bunun yerine yapılandırmayı aşağıda açıklandığı gibi güncelleştirebilirsiniz.

OAuth kimlik sağlayıcısı yapılandırmasını güncelleme

Bir OAuth kimlik sağlayıcısını etkinleştirmek veya devre dışı bırakmak ya da projenizin istemci yapılandırmasını güncellemek için öncelikle, projects.defaultSupportedIdpConfigs uç noktasına bir GET isteği göndererek sağlayıcının mevcut yapılandırmasını alın. Ardından, yapılandırmada istediğiniz değişiklikleri yapın ve yeni yapılandırmayı projects.defaultSupportedIdpConfigs uç noktasına YAMAYIN.

Örneğin, Node.js'yi kullanarak:

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);

Projeniz için daha önce yapılandırmadığınız bir kimlik sağlayıcının yapılandırmasını güncellemeye çalışırsanız çağrılar 404 HTTP hatasını döndürür. Bunun yerine, önceki bölümde gösterildiği gibi yeni bir kimlik sağlayıcısı yapılandırın.