以编程方式为 Firebase Authentication 配置 OAuth 身份提供商
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
您可以使用 Google Cloud Identity Platform REST API 以编程方式管理 Firebase 项目的 OAuth 身份提供商 (IdP) 配置。借助此 API,您可以配置想要支持的身份提供商,以及更新、启用和停用项目的当前 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) 配置,请使用 POST 方法将将新的配置发布到 projects.defaultSupportedIdpConfigs
端点。
您需要指定身份提供商的 ID 以及您的客户端 ID 和客户端密钥(通常从提供商的开发者网站获取)。以下是 Firebase 支持的身份提供商及其 ID:
提供商 |
身份提供商 ID |
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 身份提供商,或更新项目的客户端配置,请先向 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);
如果尝试更新从未为项目配置过的某个身份提供商的配置,则调用将返回 HTTP 错误 404。请转而按照上一部分中的说明配置新的身份提供商。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-07-25。
[null,null,["最后更新时间 (UTC):2025-07-25。"],[],[],null,["You can use the [Google Cloud Identity Platform REST API](https://cloud.google.com/identity-platform/docs/reference/rest/v2/projects.defaultSupportedIdpConfigs) to\nprogrammatically manage a Firebase project's OAuth identity provider (IdP)\nconfiguration. With this API, you can configure the identity providers you want\nto support, and update, enable, and disable your project's current OAuth\nconfigurations.\n\nGet authorization\n\nBefore you can call the REST API, you need an OAuth 2.0 access token that grants\nEditor access to your Firebase project. For example, to get an access token\nusing a service account in Node.js: \n\n const googleAuth = require('google-auth-library');\n const SCOPES = ['https://www.googleapis.com/auth/cloud-platform'];\n\n async function getAccessToken() {\n const serviceAccount = require('/path/to/service_account_key.json');\n const jwtClient = new googleAuth.JWT(\n serviceAccount.client_email,\n null,\n serviceAccount.private_key,\n SCOPES,\n null\n );\n return jwtClient.authorize().then((tokens) =\u003e tokens.access_token);\n }\n\nAdd a new OAuth identity provider configuration\n\nTo add a new OAuth identity provider (IdP) configuration, POST the new\nconfiguration to the [`projects.defaultSupportedIdpConfigs`](https://cloud.google.com/identity-platform/docs/reference/rest/v2/projects.defaultSupportedIdpConfigs/create)\nendpoint.\n\nYou will need to specify the ID of the identity provider and your client ID and\nclient secret, which you typically get from the provider's developer site. Here\nare the identity providers that Firebase supports and their IDs:\n\n| Provider | IdP ID |\n|-------------------|------------------------|\n| Apple | `apple.com` |\n| Apple Game Center | `gc.apple.com` |\n| Facebook | `facebook.com` |\n| GitHub | `github.com` |\n| Google | `google.com` |\n| Google Play Games | `playgames.google.com` |\n| LinkedIn | `linkedin.com` |\n| Microsoft | `microsoft.com` |\n| Twitter | `twitter.com` |\n| Yahoo | `yahoo.com` |\n\nFor example, using Node.js: \n\n const fetch = require('node-fetch');\n const GCIP_API_BASE = 'https://identitytoolkit.googleapis.com/v2';\n\n async function addIdpConfig(projectId, accessToken, idpId, clientId, clientSecret) {\n const uri = `${GCIP_API_BASE}/projects/${projectId}/defaultSupportedIdpConfigs?idpId=${idpId}`;\n const options = {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${accessToken}`\n },\n body: JSON.stringify({\n name: `projects/${projectId}/defaultSupportedIdpConfigs/${idpId}`,\n enabled: true,\n clientId: clientId,\n clientSecret: clientSecret,\n }),\n };\n return fetch(uri, options).then((response) =\u003e {\n if (response.ok) {\n return response.json();\n } else if (response.status == 409) {\n throw new Error('IdP configuration already exists. Update it instead.');\n } else {\n throw new Error('Server error.');\n }\n });\n }\n\n (async () =\u003e {\n const projectId = 'your-firebase-project-id';\n const accessToken = await getAccessToken();\n const idpId = 'facebook.com';\n const clientId = 'your-facebook-client-id';\n const clientSecret = 'your-facebook-client-secret';\n try {\n await addIdpConfig(projectId, accessToken, idpId, clientId, clientSecret);\n } catch (err) {\n console.error(err.message);\n }\n })().catch(console.error);\n\nIf the call succeeds, it returns the newly-created configuration. For example: \n\n {\n name: 'projects/your-numerical-project-id/defaultSupportedIdpConfigs/facebook.com',\n enabled: true,\n clientId: 'your-facebook-client-id',\n clientSecret: 'your-facebook-client-secret'\n }\n\nIf you try to configure an identity provider that has already been configured\nfor your project, the call returns HTTP error 409. In this situation, you can\nupdate the configuration instead, as described below.\n\nUpdate an OAuth identity provider configuration\n\nTo enable or disable an OAuth identity provider, or update your project's client\nconfiguration, first get the provider's current configuration by making a GET\nrequest to the the [`projects.defaultSupportedIdpConfigs`](https://cloud.google.com/identity-platform/docs/reference/rest/v2/projects.defaultSupportedIdpConfigs/get) endpoint.\nThen, make the changes you want to the configuration and PATCH the new\nconfiguration to the [`projects.defaultSupportedIdpConfigs`](https://cloud.google.com/identity-platform/docs/reference/rest/v2/projects.defaultSupportedIdpConfigs/patch)\nendpoint.\n\nFor example, using Node.js: \n\n async function getIdpCfg(projectId, accessToken, idpId) {\n const uri = `${GCIP_API_BASE}/projects/${projectId}/defaultSupportedIdpConfigs/${idpId}`;\n const options = {\n method: 'GET',\n headers: {\n 'Authorization': `Bearer ${accessToken}`\n },\n };\n return fetch(uri, options).then((response) =\u003e {\n if (response.ok) {\n return response.json();\n } else if (response.status == 404) {\n throw new Error('IdP configuration not found. First add the IdP'\n + ' configuration to your project.');\n } else {\n throw new Error('Server error.');\n }\n });\n }\n\n async function updateIdpConfig(accessToken, idpCfg) {\n const uri = `${GCIP_API_BASE}/${idpCfg.name}`;\n const options = {\n method: 'PATCH',\n headers: {\n 'Authorization': `Bearer ${accessToken}`\n },\n body: JSON.stringify(idpCfg),\n };\n return fetch(uri, options).then((response) =\u003e {\n if (response.ok) {\n return response.json();\n } else if (response.status == 404) {\n throw new Error('IdP configuration not found. First add the IdP'\n + ' configuration to your project.');\n } else {\n throw new Error('Server error.');\n }\n });\n }\n\n (async () =\u003e {\n const projectId = 'your-firebase-project-id';\n const accessToken = await getAccessToken();\n const idpId = 'facebook.com';\n try {\n // Get the IdP's current configuration.\n const idpCfg = await getIdpCfg(projectId, accessToken, idpId);\n\n // Update the configuration. (For example, disable the IdP.)\n idpCfg.enabled = false;\n await updateIdpConfig(accessToken, idpCfg);\n } catch (err) {\n console.error(err.message);\n }\n })().catch(console.error);\n\nIf you try to update the configuration of an identity provider you've never\nconfigured for your project, the calls will return HTTP error 404. Instead,\nconfigure a new identity provider as shown in the [previous\nsection](#add-idpcfg)."]]