使用 SAML 登录用户
本文档介绍如何使用 Identity Platform 让用户通过安全断言标记语言 (SAML) 2.0 提供方登录。
准备工作
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
- 启用 Identity Platform,并将客户端 SDK 添加到您的应用。如需了解详情和说明,请参阅通过 Identity Platform 让用户使用电子邮件登录快速入门。
配置 Provider
在 Google Cloud 控制台中,前往 Identity Platform > 身份提供方页面。
前往“身份提供方”点击添加提供商,然后从列表中选择 SAML。
输入以下详细信息:
提供商的名称。此名称可以与提供商 ID 相同,也可以是自定义名称。如果要输入自定义名称,请点击提供商 ID 旁边的修改以指定 ID(必须以
saml开头)。提供商的实体 ID。
提供商的 SAML SSO 网址。
用于对提供商进行令牌签名的证书。请确保包含开始字符串和结束字符串。例如:
-----BEGIN CERTIFICATE----- MIICajCCAdOgAwIBAgIBADANBgkqhkiG9w0BAQ0FADBSMQswCQYDVQQGEwJ1czEL ... LEzc1JwEGQQVDYQCwsQMSBDAF0QAB0w9GikhqkgBNADABIgABIwAgOdACCjaCIIM -----END CERTIFICATE-----
在服务提供商部分中,输入应用的实体 ID。这通常是应用的网址。SAML 身份提供商称之为受众。
在项目设置侧边栏中,点击添加网域,然后添加应用的网域。例如,如果应用的登录网址为
https://example.com/login,请添加example.com。如需完成设置,请执行以下任一操作:
从授权回调(网址)字段中复制默认授权回调网址,并将其添加到您的 SAML 应用配置中。
使用默认授权回调网址可降低验证 SAML 响应的复杂性。
在您的 SAML 应用配置中添加自定义授权回调网址,例如
https://PROJECT-ID.firebaseapp.com/__/auth/handler。
在配置您的应用部分,点击设置详细信息。 将代码段复制到应用的代码中,以初始化 Identity Platform Client SDK。
点击保存。
提供方必需元素
Identity Platform 预期提供方在响应中提供 <saml:Subject> 和 <saml:NameID> 元素。如果您在配置提供方时未定义这些元素的值,SAML 断言会失败。
对请求进行签名
您可以通过对身份验证请求进行签名来增强其安全性。
如需对请求进行签名,请先调用 inboundSamlConfigs.patch() 并将 idp_config.sign_request 设置为 true,为您的身份提供方启用签名请求:
REST
在使用任何请求数据之前,请先进行以下替换:
project-id: Google Cloud 项目的 IDprovider-id:SAML 提供方 ID
HTTP 方法和网址:
PATCH https://identitytoolkit.googleapis.com/admin/v2/projects/project-id/inboundSamlConfigs/provider-id?updateMask=idpConfig.signRequest
请求 JSON 正文:
{
"idp_config": {
"sign_request": true
}
}
如需发送您的请求,请展开以下选项之一:
您必须使用 REST API 来启用签名请求;不支持使用Google Cloud 控制台或 Google Cloud CLI。
响应是一个 InboundSamlConfig 对象,它包含一组 SpCertificate 对象。
使用您的 SAML 身份提供商配置 X509 证书的值,以便它能够验证请求的签名。
轮替服务提供商证书
启用已签名的 SAML 请求后,Identity Platform 会生成一个有效期为五年的服务提供商 (SP) 证书。此证书过期后,您的身份提供方 (IdP) 会拒绝身份验证请求,用户将无法登录。为防止身份验证中断,请监控 SP 证书的失效日期,并在证书失效之前进行轮替。
Identity Platform 会将 SP 证书限定在您的项目或租户范围内,并在该项目或租户中的所有 SAML 配置(InboundSamlConfig 对象)之间共享这些证书。为一个 SAML 配置轮替 SP 证书会轮替同一项目或租户中所有其他 SAML 配置的证书。
如需查看失效日期并轮替 SP 证书,请执行以下操作:
如需检查 SP 证书过期时间,请使用
jq提取证书过期时间戳:curl -s -X GET \ "https://identitytoolkit.googleapis.com/v2/projects/PROJECT_ID/inboundSamlConfigs" \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "X-Goog-User-Project: PROJECT_ID" \ -H "Content-Type: application/json" | \ jq -r '.inboundSamlConfigs[].spConfig.spCertificates[]?.expiresAt'对于租户级 SAML 配置,请在请求网址中添加
/tenants/TENANT_ID:curl -s -X GET \ "https://identitytoolkit.googleapis.com/v2/projects/PROJECT_ID/tenants/TENANT_ID/inboundSamlConfigs" \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "X-Goog-User-Project: PROJECT_ID" \ -H "Content-Type: application/json" | \ jq -r '.inboundSamlConfigs[].spConfig.spCertificates[]?.expiresAt'替换以下内容:
PROJECT_ID: Google Cloud项目 ID。TENANT_ID:租户级 SAML 配置的租户 ID。
检查
spConfig.spCertificates数组中的expiresAt值。如果到期时间戳 (
expiresAt) 在 30 天内或贵组织要求的时间范围内,请与 IdP 管理员协调,安排证书更新的停机时间。在预定的停机时间内,通过向
inboundSamlConfigs.rotateCertificate端点发送POST请求来轮替服务提供商证书。目标 SAML 配置必须将idpConfig.signRequest字段设置为true。否则,请求将失败并显示INVALID_CONFIG错误:curl -s -X POST \ "https://identitytoolkit.googleapis.com/v2/projects/PROJECT_ID/inboundSamlConfigs/PROVIDER_ID:rotateCertificate" \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "X-Goog-User-Project: PROJECT_ID" \ -H "Content-Type: application/json" \ -d "{}"对于租户级 SAML 配置,请在请求网址中添加
/tenants/TENANT_ID:curl -s -X POST \ "https://identitytoolkit.googleapis.com/v2/projects/PROJECT_ID/tenants/TENANT_ID/inboundSamlConfigs/PROVIDER_ID:rotateCertificate" \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "X-Goog-User-Project: PROJECT_ID" \ -H "Content-Type: application/json" \ -d "{}"替换以下内容:
PROJECT_ID: Google Cloud项目 ID。PROVIDER_ID:SAML 提供方 ID,以saml.开头。此配置必须将idpConfig.signRequest字段设置为true。TENANT_ID:租户级 SAML 配置的租户 ID。
响应会返回一个
inboundSamlConfig对象,其中包含新生成的 X.509 证书 (x509Certificate) 及其在inboundSamlConfig.spConfig.spCertificates数组中的新到期时间戳 (expiresAt)。如需更新 IdP 中的证书配置,请从响应中复制新的
x509Certificate值,并将其分享给项目或租户中每个使用签名请求的 SAML 配置的 IdP 管理员。测试单点登录是否可与更新后的配置搭配使用。
让用户登录
当您让用户登录时,客户端 SDK 会处理身份验证握手,然后返回在其载荷中包含 SAML 属性的 ID 令牌。要登录用户并从 SAML 提供商获取特性,请执行以下操作:
使用您在上一部分中配置的提供商 ID 创建
SAMLAuthProvider实例。提供商 ID 必须以saml开头。Web 版本 9
import { SAMLAuthProvider } from "firebase/auth"; const provider = new SAMLAuthProvider("saml.myProvider");
Web 版本 8
const provider = new firebase.auth.SAMLAuthProvider('saml.myProvider');
启动登录流程。您可以选择使用对话框或重定向。
弹出式内容
Web 版本 9
import { getAuth, signInWithPopup, SAMLAuthProvider } from "firebase/auth"; const auth = getAuth(); signInWithPopup(auth, provider) .then((result) => { // User is signed in. // Provider data available from the result.user.getIdToken() // or from result.user.providerData }).catch((error) => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; // The email of the user's account used. const email = error.customData.email; // The AuthCredential type that was used. const credential = SAMLAuthProvider.credentialFromError(error); // Handle / display error. // ... });
Web 版本 8
firebase.auth().signInWithPopup(provider) .then((result) => { // User is signed in. // Identity provider data available in result.additionalUserInfo.profile, // or from the user's ID token obtained from result.user.getIdToken() // as an object in the firebase.sign_in_attributes custom claim // This is also available from result.user.getIdTokenResult() // idTokenResult.claims.firebase.sign_in_attributes. }) .catch((error) => { // Handle / display error. // ... });
重定向
如需重定向到登录页面,请调用
signInWithRedirect():Web 版本 9
import { getAuth, signInWithRedirect } from "firebase/auth"; const auth = getAuth(); signInWithRedirect(auth, provider);
Web 版本 8
firebase.auth().signInWithRedirect(provider);
然后,在用户返回到您的应用时,调用
getRedirectResult()获取结果:Web 版本 9
import { getAuth, getRedirectResult, SAMLAuthProvider } from "firebase/auth"; const auth = getAuth(); getRedirectResult(auth) .then((result) => { // User is signed in. // Provider data available from the result.user.getIdToken() // or from result.user.providerData }) .catch((error) => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; // The email of the user's account used. const email = error.customData.email; // The AuthCredential type that was used. const credential = SAMLAuthProvider.credentialFromError(error); // Handle / display error. // ... });
Web 版本 8
firebase.auth().getRedirectResult() .then((result) => { // User is signed in. // Provider data available in result.additionalUserInfo.profile, // or from the user's ID token obtained from result.user.getIdToken() // as an object in the firebase.sign_in_attributes custom claim // This is also available from result.user.getIdTokenResult() // idTokenResult.claims.firebase.sign_in_attributes. }).catch((error) => { // Handle / display error. // ... });
使用
firebase.sign_in_attributes声明从 ID 令牌中检索与 SAML 提供商相关的用户特性。在将 ID 令牌 发送到服务器时,务必使用 Admin SDK 验证 ID 令牌。只有在身份提供方的 SAML 断言的
NameID属性中提供了用户的邮箱,它才会包含在 ID 令牌中:<Subject> <NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">test@email.com</NameID> </Subject>此信息会填充到 Firebase 颁发的 ID 令牌和 UserInfo 对象中。
仅支持客户端 SDK 中由服务提供方启动的 SAML 流程。
关联用户账号
如果用户已使用其他方法(例如电子邮件地址/密码)登录您的应用,您可以使用 linkWithPopup() 或 linkWithRedirect() 将其现有账号关联到 SAML 提供方。
以下代码段展示了如何将用户的 Google 账号关联到 SAML 提供方:
Web 版本 9
import { getAuth, linkWithPopup, GoogleAuthProvider } from "firebase/auth"; const provider = new GoogleAuthProvider(); const auth = getAuth(); linkWithPopup(auth.currentUser, provider).then((result) => { // Accounts successfully linked. const credential = GoogleAuthProvider.credentialFromResult(result); const user = result.user; // ... }).catch((error) => { // Handle Errors here. // ... });
Web 版本 8
auth.currentUser.linkWithPopup(provider).then((result) => { // Accounts successfully linked. var credential = result.credential; var user = result.user; // ... }).catch((error) => { // Handle Errors here. // ... });