首页 > 解决方案 > 如何使用 FirebaseUser 设置自定义声明?

问题描述

我正在尝试向自定义声明添加一些键值对,但找不到任何功能。你如何在Android上做到这一点?

例如,我可以这样设置显示照片:

FirebaseUser user = ...;
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                            .setPhotoUri(Uri.parse(response.body().getPhotoURI()))
                            .build();

user.updateProfile(profileUpdates).addOnCompleteListener(task -> { ... });

标签: javaandroidfirebasefirebase-authentication

解决方案


客户端 SDK 存在风险,因为恶意客户端也可以修改数据。可能现在可以在控制台中添加声明,我不确定。这可能就是您正在寻找的东西。从使用 Firebase Auth 自定义声明控制数据访问

将各种标准添加为自定义声明听起来可能是个好主意。例如,您可能想要添加家庭住址、其他照片 URL 或个人资料描述。但这不是自定义声明的设计目的。地址之类的数据应该存储在数据库中,因为它与身份验证无关。令牌不是配置文件!

通过Admin SDK 设置和验证自定义用户声明

自定义声明可能包含敏感数据,因此它们只能由 Firebase Admin SDK 从特权服务器环境中设置。

// Set admin privilege on the user corresponding to uid.
Map<String, Object> claims = new HashMap<>();
claims.put("admin", true);
FirebaseAuth.getInstance().setCustomUserClaims(uid, claims);

下次发布新的自定义声明时,新的自定义声明将传播到用户的 ID 令牌。

并使用它:

// 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.
}

或作为客户:

// Lookup the user associated with the specified uid.
UserRecord user = FirebaseAuth.getInstance().getUser(uid);
boolean claim = Boolean.parseBoolean(user.getCustomClaims().get("admin"));

您可能想阅读以下内容:Firebase Custom Claim Java


推荐阅读