为用户配置自定义声明
本文档介绍如何使用 Identity Platform 为用户配置自定义声明。在身份验证期间,自定义声明会被插入用户令牌。您的应用可以使用这些声明来处理复杂的授权场景,例如根据用户角色限制用户对资源的访问权限。
设置自定义声明
为了保证安全性,请在服务器上使用 Admin SDK 设置自定义声明:
安装 Admin SDK(如果您尚未安装)。
设置您要使用的自定义声明。以下示例对用户设置了自定义声明,以描述他们是管理员:
Node.js
// Set admin privilege on the user corresponding to uid. getAuth() .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. });
Java
// Set admin privilege on the user corresponding to uid. Map<String, Object> claims = new HashMap<>(); claims.put("admin", true); FirebaseAuth.getInstance().setCustomUserClaims(uid, claims); // The new custom claims will propagate to the user's ID token the // next time a new one is issued.
Python
# Set admin privilege on the user corresponding to uid. auth.set_custom_user_claims(uid, {'admin': True}) # The new custom claims will propagate to the user's ID token the # next time a new one is issued.
Go
// Get an auth client from the firebase.App client, err := app.Auth(ctx) if err != nil { log.Fatalf("error getting Auth client: %v\n", err) } // Set admin privilege on the user corresponding to uid. claims := map[string]interface{}{"admin": true} err = client.SetCustomUserClaims(ctx, uid, claims) if err != nil { log.Fatalf("error setting custom claims %v\n", err) } // The new custom claims will propagate to the user's ID token the // next time a new one is issued.
C#
// Set admin privileges on the user corresponding to uid. var claims = new Dictionary<string, object>() { { "admin", true }, }; await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(uid, claims); // The new custom claims will propagate to the user's ID token the // next time a new one is issued.
在下一次自定义声明被发送到您的服务器时,验证该声明:
Node.js
// Verify the ID token first. getAuth() .verifyIdToken(idToken) .then((claims) => { if (claims.admin === true) { // Allow access to requested admin resource. } });
Java
// Verify the ID token first. FirebaseToken decoded = FirebaseAuth.getInstance().verifyIdToken(idToken); if (Boolean.TRUE.equals(decoded.getClaims().get("admin"))) { // Allow access to requested admin resource. }
Python
# Verify the ID token first. claims = auth.verify_id_token(id_token) if claims['admin'] is True: # Allow access to requested admin resource. pass
Go
// Verify the ID token first. token, err := client.VerifyIDToken(ctx, idToken) if err != nil { log.Fatal(err) } claims := token.Claims if admin, ok := claims["admin"]; ok { if admin.(bool) { //Allow access to requested admin resource. } }
C#
// Verify the ID token first. FirebaseToken decoded = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken); object isAdmin; if (decoded.Claims.TryGetValue("admin", out isAdmin)) { if ((bool)isAdmin) { // Allow access to requested admin resource. } }
确定要向用户显示哪些自定义声明:
Node.js
// Lookup the user associated with the specified uid. getAuth() .getUser(uid) .then((userRecord) => { // The claims can be accessed on the user record. console.log(userRecord.customClaims['admin']); });
Java
// Lookup the user associated with the specified uid. UserRecord user = FirebaseAuth.getInstance().getUser(uid); System.out.println(user.getCustomClaims().get("admin"));
Python
# Lookup the user associated with the specified uid. user = auth.get_user(uid) # The claims can be accessed on the user record. print(user.custom_claims.get('admin'))
Go
// Lookup the user associated with the specified uid. user, err := client.GetUser(ctx, uid) if err != nil { log.Fatal(err) } // The claims can be accessed on the user record. if admin, ok := user.CustomClaims["admin"]; ok { if admin.(bool) { log.Println(admin) } }
C#
// Lookup the user associated with the specified uid. UserRecord user = await FirebaseAuth.DefaultInstance.GetUserAsync(uid); Console.WriteLine(user.CustomClaims["admin"]);
设置自定义声明时,请注意以下事项:
- 自定义声明不得超过 1000 字节。尝试传递大于 1000 字节的声明会导致错误。
- 令牌颁发后,自定义声明会被插入用户 JWT 中。在令牌刷新之前,新声明不可用。您可以通过调用
user.getIdToken(true)
静默刷新令牌。 - 为保持连续性和安全性,请仅在安全服务器环境中设置自定义声明。
后续步骤
- 详细了解屏蔽函数,此类函数还可用于设置自定义声明。
- 如需详细了解 Identity Platform 自定义声明,请参阅 Admin SDK 参考文档。