使用 OpenID Connect 进行身份验证(Web 应用)
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
如果您已升级到 Firebase Authentication with Identity Platform,则可以使用所选的 OpenID Connect (OIDC) 合规提供方对用户进行 Firebase 身份验证。这样,您就可以使用 Firebase 不提供原生支持的身份提供方。
准备工作
如需让用户使用 OIDC 提供方登录,您必须先从该提供方处收集一些信息:
客户端 ID:提供方用于标识您的应用的唯一字符串。您的提供方可能会针对您支持的每个平台为您分配一个不同的客户端 ID。这是您的提供方发放的 ID 令牌中的 aud
声明值之一。
客户端密钥:提供方用于确认客户端 ID 所有权的密钥字符串。对于每个客户端 ID,您都需要一个匹配的客户端密钥。(仅当您使用身份验证代码流程 [强烈建议使用] 时才需要此值。)
发放者:用于标识您的提供方的字符串。此值必须是网址,在附加 /.well-known/openid-configuration
后表示提供方的 OIDC 发现文档的位置。例如,如果发放者为 https://auth.example.com
,则发现文档必须在 https://auth.example.com/.well-known/openid-configuration
位置提供。
获得上述信息后,启用 OpenID Connect 作为 Firebase 项目的登录提供方:
将 Firebase 添加至您的 JavaScript 项目。
如果您尚未升级到 Firebase Authentication with Identity Platform,请升级。OpenID Connect 身份验证仅适用于升级后的项目。
在 Firebase 控制台的登录提供方页面上,点击添加新提供方,然后点击 OpenID Connect。
选择是要使用授权代码流程还是隐式授权流程。
如果提供方支持,您应始终使用代码流程。隐式流程的安全性较低,强烈建议不要使用。
为此提供方命名。请记下系统生成的提供方 ID(类似于 oidc.example-provider
)。向应用添加登录代码时,您需要用到此 ID。
指定您的客户端 ID 和客户端密钥,以及提供方的发放者字符串。这些值必须与提供方分配给您的值完全一致。
保存更改。
使用 Firebase SDK 处理登录流程
如果您想要使用 OIDC 提供方通过 Firebase 验证用户身份,较简单的方法是使用 Firebase SDK 来处理整个登录流程。
如需使用 Firebase JavaScript SDK 处理登录流程,请按以下步骤操作:
使用您在 Firebase 控制台中获得的提供方 ID 创建 OAuthProvider
实例。
Web
import { OAuthProvider } from "firebase/auth";
const provider = new OAuthProvider('oidc.example-provider');
Web
var provider = new firebase.auth.OAuthProvider('oidc.example-provider');
可选:指定您希望通过 OAuth 请求发送的其他自定义 OAuth 参数。
Web
provider.setCustomParameters({
// Target specific email with login hint.
login_hint: 'user@example.com'
});
Web
provider.setCustomParameters({
// Target specific email with login hint.
login_hint: 'user@example.com'
});
请与您的提供方联系,了解其支持的参数。请注意,您不能使用 setCustomParameters
传递 Firebase 必需的参数。这些参数包括 client_id
、response_type
、redirect_uri
、state
、scope
和 response_mode
。
可选:指定您希望向身份验证提供方申请获取的个人资料基本信息以外的额外 OAuth 2.0 范围。
Web
provider.addScope('mail.read');
provider.addScope('calendars.read');
Web
provider.addScope('mail.read');
provider.addScope('calendars.read');
请与您的提供方联系,了解其支持的范围。
使用 OAuth 提供方对象进行 Firebase 身份验证。
您可以将用户重定向到提供方的登录页面,也可以在弹出式浏览器窗口中打开登录页面。
重定向流程
调用 signInWithRedirect()
重定向到提供方登录页面:
Web
import { getAuth, signInWithRedirect } from "firebase/auth";
const auth = getAuth();
signInWithRedirect(auth, provider);
Web
firebase.auth().signInWithRedirect(provider);
用户完成登录并返回到您的应用后,您可以调用 getRedirectResult()
获取登录结果。
Web
import { getAuth, getRedirectResult, OAuthProvider } from "firebase/auth";
const auth = getAuth();
getRedirectResult(auth)
.then((result) => {
// User is signed in.
// IdP data available in result.additionalUserInfo.profile.
// Get the OAuth access token and ID Token
const credential = OAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
const idToken = credential.idToken;
})
.catch((error) => {
// Handle error.
});
Web
firebase.auth().getRedirectResult()
.then((result) => {
// IdP data available in result.additionalUserInfo.profile.
// ...
/** @type {firebase.auth.OAuthCredential} */
var credential = result.credential;
// OAuth access and id tokens can also be retrieved:
var accessToken = credential.accessToken;
var idToken = credential.idToken;
})
.catch((error) => {
// Handle error.
});
弹出式窗口流程
Web
import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth";
const auth = getAuth();
signInWithPopup(auth, provider)
.then((result) => {
// User is signed in.
// IdP data available using getAdditionalUserInfo(result)
// Get the OAuth access token and ID Token
const credential = OAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
const idToken = credential.idToken;
})
.catch((error) => {
// Handle error.
});
Web
firebase.auth().signInWithPopup(provider)
.then((result) => {
// IdP data available in result.additionalUserInfo.profile.
// ...
/** @type {firebase.auth.OAuthCredential} */
var credential = result.credential;
// OAuth access and id tokens can also be retrieved:
var accessToken = credential.accessToken;
var idToken = credential.idToken;
})
.catch((error) => {
// Handle error.
});
以上示例侧重的是登录流程。除此之外,您也可以使用同一模式通过 linkWithRedirect()
和 linkWithPopup()
将 OIDC 提供方与现有用户相关联,然后使用 reauthenticateWithRedirect()
和 reauthenticateWithPopup()
(可用于为要求用户在近期登录的敏感操作检索新的凭据)重新验证用户身份。
手动处理登录流程
如果您已在应用中实现了 OpenID Connect 登录流程,可以直接使用 ID 令牌通过 Firebase 进行身份验证:
Web
import { getAuth, signInWithCredential, OAuthProvider } from "firebase/auth";
const provider = new OAuthProvider("oidc.example-provider");
const credential = provider.credential({
idToken: idToken,
});
signInWithCredential(getAuth(), credential)
.then((result) => {
// User is signed in.
// IdP data available in result.additionalUserInfo.profile.
// Get the OAuth access token and ID Token
const credential = OAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
const idToken = credential.idToken;
})
.catch((error) => {
// Handle error.
});
Web
const provider = new OAuthProvider("oidc.example-provider");
const credential = provider.credential({
idToken: idToken,
});
firebase.auth().signInWithCredential(credential)
.then((result) => {
// User is signed in.
// IdP data available in result.additionalUserInfo.profile.
// Get the OAuth access token and ID Token
const credential = OAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
const idToken = credential.idToken;
})
.catch((error) => {
// Handle error.
});
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-08。
[null,null,["最后更新时间 (UTC):2025-08-08。"],[],[],null,["If you've upgraded to Firebase Authentication with Identity Platform, you can authenticate your users with\nFirebase using the OpenID Connect (OIDC) compliant provider of your choice. This\nmakes it possible to use identity providers not natively supported by Firebase.\n\nBefore you begin\n\nTo sign in users using an OIDC provider, you must first collect some information\nfrom the provider:\n\n- **Client ID** : A string unique to the provider that identifies your app. Your\n provider might assign you a different client ID for each platform you support.\n This is one of the values of the `aud` claim in ID tokens issued by your\n provider.\n\n- **Client secret** : A secret string that the provider uses to confirm ownership\n of a client ID. For every client ID, you will need a matching client secret.\n (This value is required only if you're using the *auth code flow*, which is\n strongly recommended.)\n\n- **Issuer** : A string that identifies your provider. This value must be a URL\n that, when appended with `/.well-known/openid-configuration`, is the location\n of the provider's OIDC discovery document. For example, if the issuer is\n `https://auth.example.com`, the discovery document must be available at\n `https://auth.example.com/.well-known/openid-configuration`.\n\nAfter you have the above information, enable OpenID Connect as a sign-in\nprovider for your Firebase project:\n\n1. [Add Firebase to your JavaScript project](/docs/web/setup).\n\n2. If you haven't upgraded to Firebase Authentication with Identity Platform, do so. OpenID Connect authentication\n is only available in upgraded projects.\n\n3. On the [**Sign-in providers**](//console.firebase.google.com/project/_/authentication/providers)\n page of the Firebase console, click **Add new provider** , and then click\n **OpenID Connect**.\n\n4. Select whether you will be using the *authorization code flow* or the\n *implicit grant flow*.\n\n **You should use always the code flow if your provider supports it**. The\n implicit flow is less secure and using it is strongly discouraged.\n5. Give a name to this provider. Note the provider ID that's generated:\n something like `oidc.example-provider`. You'll need this ID when you add\n sign-in code to your app.\n\n6. Specify your client ID and client secret, and your provider's issuer string.\n These values must exactly match the values your provider assigned to you.\n\n7. Save your changes.\n\nHandle the sign-in flow with the Firebase SDK\n\nThe easiest way to authenticate your users with Firebase using your OIDC\nprovider is to handle the entire sign-in flow with the Firebase SDK.\n\nTo handle the sign-in flow with the Firebase JavaScript SDK, follow these\nsteps:\n\n1. Create an instance of an `OAuthProvider` using the provider ID you got in\n the Firebase console.\n\n Web \n\n import { OAuthProvider } from \"firebase/auth\";\n\n const provider = new OAuthProvider('oidc.example-provider');\n\n Web \n\n var provider = new firebase.auth.OAuthProvider('oidc.example-provider');\n\n2. **Optional**: Specify additional custom OAuth parameters that you want to\n send with the OAuth request.\n\n Web \n\n provider.setCustomParameters({\n // Target specific email with login hint.\n login_hint: 'user@example.com'\n });\n\n Web \n\n provider.setCustomParameters({\n // Target specific email with login hint.\n login_hint: 'user@example.com'\n });\n\n Check with your provider for the parameters it supports.\n Note that you can't pass Firebase-required parameters with\n `setCustomParameters`. These parameters are `client_id`,\n `response_type`, `redirect_uri`, `state`, `scope` and\n `response_mode`.\n3. **Optional**: Specify additional OAuth 2.0 scopes beyond basic profile that\n you want to request from the authentication provider.\n\n Web \n\n provider.addScope('mail.read');\n provider.addScope('calendars.read');\n\n Web \n\n provider.addScope('mail.read');\n provider.addScope('calendars.read');\n\n Check with your provider for the scopes it supports.\n4. Authenticate with Firebase using the OAuth provider object.\n\n You can either redirect the user to the provider's sign-in page or open the\n sign-in page in a pop-up browser window.\n\n **Redirect flow**\n\n Redirect to the provider sign-in page by calling `signInWithRedirect()`: \n\n Web \n\n import { getAuth, signInWithRedirect } from \"firebase/auth\";\n\n const auth = getAuth();\n signInWithRedirect(auth, provider);\n\n Web \n\n firebase.auth().signInWithRedirect(provider);\n\n After the user completes sign-in and returns to your app, you can obtain the\n sign-in result by calling `getRedirectResult()`. \n\n Web \n\n import { getAuth, getRedirectResult, OAuthProvider } from \"firebase/auth\";\n\n const auth = getAuth();\n getRedirectResult(auth)\n .then((result) =\u003e {\n // User is signed in.\n // IdP data available in result.additionalUserInfo.profile.\n\n // Get the OAuth access token and ID Token\n const credential = OAuthProvider.credentialFromResult(result);\n const accessToken = credential.accessToken;\n const idToken = credential.idToken;\n })\n .catch((error) =\u003e {\n // Handle error.\n });\n\n Web \n\n firebase.auth().getRedirectResult()\n .then((result) =\u003e {\n // IdP data available in result.additionalUserInfo.profile.\n // ...\n\n /** @type {firebase.auth.OAuthCredential} */\n var credential = result.credential;\n\n // OAuth access and id tokens can also be retrieved:\n var accessToken = credential.accessToken;\n var idToken = credential.idToken;\n })\n .catch((error) =\u003e {\n // Handle error.\n });\n\n **Pop-up flow** \n\n Web \n\n import { getAuth, signInWithPopup, OAuthProvider } from \"firebase/auth\";\n\n const auth = getAuth();\n signInWithPopup(auth, provider)\n .then((result) =\u003e {\n // User is signed in.\n // IdP data available using getAdditionalUserInfo(result)\n\n // Get the OAuth access token and ID Token\n const credential = OAuthProvider.credentialFromResult(result);\n const accessToken = credential.accessToken;\n const idToken = credential.idToken;\n })\n .catch((error) =\u003e {\n // Handle error.\n });\n\n Web \n\n firebase.auth().signInWithPopup(provider)\n .then((result) =\u003e {\n // IdP data available in result.additionalUserInfo.profile.\n // ...\n\n /** @type {firebase.auth.OAuthCredential} */\n var credential = result.credential;\n\n // OAuth access and id tokens can also be retrieved:\n var accessToken = credential.accessToken;\n var idToken = credential.idToken;\n })\n .catch((error) =\u003e {\n // Handle error.\n });\n\n5. While the above examples focus on sign-in flows, you can use the same\n pattern to link an OIDC provider to an existing user using\n `linkWithRedirect()` and `linkWithPopup()`, and re-authenticate a user with\n `reauthenticateWithRedirect()` and `reauthenticateWithPopup()`, which can be\n used to retrieve fresh credentials for sensitive operations that require\n recent login.\n\nHandle the sign-in flow manually\n\nIf you've already implemented the OpenID Connect sign-in flow in your app, you\ncan use the ID token directly to authenticate with Firebase: \n\nWeb \n\n import { getAuth, signInWithCredential, OAuthProvider } from \"firebase/auth\";\n\n const provider = new OAuthProvider(\"oidc.example-provider\");\n const credential = provider.credential({\n idToken: idToken,\n });\n signInWithCredential(getAuth(), credential)\n .then((result) =\u003e {\n // User is signed in.\n // IdP data available in result.additionalUserInfo.profile.\n\n // Get the OAuth access token and ID Token\n const credential = OAuthProvider.credentialFromResult(result);\n const accessToken = credential.accessToken;\n const idToken = credential.idToken;\n })\n .catch((error) =\u003e {\n // Handle error.\n });\n\nWeb \n\n const provider = new OAuthProvider(\"oidc.example-provider\");\n const credential = provider.credential({\n idToken: idToken,\n });\n firebase.auth().signInWithCredential(credential)\n .then((result) =\u003e {\n // User is signed in.\n // IdP data available in result.additionalUserInfo.profile.\n\n // Get the OAuth access token and ID Token\n const credential = OAuthProvider.credentialFromResult(result);\n const accessToken = credential.accessToken;\n const idToken = credential.idToken;\n })\n .catch((error) =\u003e {\n // Handle error.\n });"]]