本文档介绍如何使用 Identity Platform 为用户配置自定义声明。在身份验证期间,自定义声明会被插入用户令牌。您的应用可以使用这些声明来处理复杂的授权场景,例如根据用户角色限制用户对资源的访问权限。
准备工作
使用自定义声明
为了保证安全性,请在服务器上使用 Admin SDK 设置自定义声明。以下示例展示了如何在 Node.js 中使用自定义声明;Admin SDK 参考包含其他语言的示例。
设置您要使用的自定义声明。以下示例对用户设置了自定义声明,以描述他们是管理员:
// Set admin privilege on the user corresponding to uid. admin.auth().setCustomUserClaims(uid, {admin: true}).then(() => { // The new custom claims will propagate to the user's ID token the // next time a new one is issued. });
在下一次自定义声明被发送到您的服务器时,验证该声明:
// Verify the ID token first. admin.auth().verifyIdToken(idToken).then((claims) => { if (claims.admin === true) { // Allow access to requested admin resource. } });
确定要向用户显示哪些自定义声明:
// Lookup the user associated with the specified uid. admin.auth().getUser(uid).then((userRecord) => { // The claims can be accessed on the user record. console.log(userRecord.customClaims.admin); });
自定义声明非常强大,但您应注意以下几点:
- 自定义声明不得超过 1000 字节。尝试传递大于 1000 字节的声明会导致错误。
- 令牌颁发后,自定义声明会被插入用户 JWT 中。在令牌刷新之前,新声明不可用。您可以通过调用
user.getIdToken(true)
静默刷新令牌。 - 为保持连续性和安全性,请仅在安全服务器环境中设置自定义声明。
后续步骤
- 如需详细了解 Identity Platform 自定义声明,请参阅 Admin SDK 参考文档。