Firebase 인증에 사용할 OAuth ID 공급업체를 프로그래매틱 방식으로 구성

Google Cloud Identity Platform REST API를 사용하여 Firebase 프로젝트의 OAuth ID 공급업체(IdP) 구성을 프로그래매틱 방식으로 관리할 수 있습니다. 이 API를 사용하면 지원하려는 ID 공급업체를 구성하고 프로젝트의 현재 OAuth 구성을 업데이트, 사용 설정, 중지할 수 있습니다.

승인 가져오기

REST API를 호출하려면 Firebase 프로젝트에 편집자 액세스 권한을 부여하는 OAuth 2.0 액세스 토큰이 필요합니다. 예를 들어 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 ID 공급업체 구성 추가

새 OAuth ID 공급업체(IdP) 구성을 추가하려면 projects.defaultSupportedIdpConfigs 엔드포인트에 새 구성을 게시합니다.

ID 공급업체의 ID, 클라이언트 ID, 클라이언트 보안 비밀번호를 지정해야 합니다. 이러한 정보는 일반적으로 공급업체의 개발자 사이트에서 가져옵니다. Firebase에서 지원하는 ID 공급업체 및 ID는 다음과 같습니다.

공급업체 IdP ID
Apple apple.com
Apple Game Center 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'
}

기존에 구성된 ID 공급업체를 프로젝트에 구성하려고 하면 호출 시 HTTP 오류 409가 반환됩니다. 이 경우 아래 설명대로 구성을 업데이트하면 됩니다.

OAuth ID 공급업체 구성 업데이트

OAuth ID 공급업체를 사용 설정 또는 중지하거나 프로젝트의 클라이언트 구성을 업데이트하려면 먼저 projects.defaultSupportedIdpConfigs 엔드포인트에 GET 요청을 수행하여 공급업체의 현재 구성을 가져옵니다. 그런 다음 구성을 변경하고 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);

프로젝트에 구성한 적이 없는 ID 공급업체의 구성을 업데이트하려고 하면 호출 시 HTTP 오류 404가 반환됩니다. 대신 이전 섹션처럼 새 ID 공급업체를 구성합니다.