【问题标题】:How to set custom claims with FirebaseUser?如何使用 FirebaseUser 设置自定义声明?
【发布时间】:2020-11-11 14:30:35
【问题描述】:

我正在尝试向自定义声明添加一些键值对,但找不到任何功能。你在安卓上是怎么做到的?

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

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

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

【问题讨论】:

    标签: java android firebase firebase-authentication


    【解决方案1】:

    客户端 SDK 存在风险,因为恶意客户端也可以修改数据。可能现在可以在控制台中添加声明,我不确定。这可能就是您正在寻找的东西。来自Controlling Data Access Using Firebase Auth Custom Claims

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

    来自Set and validate custom user claims via the 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

    【讨论】:

      【解决方案2】:

      无法直接在客户端应用中设置自定义声明。这将被视为安全问题。自定义声明是一种灵活的安全机制,允许您授予用户访问后端资源的权限。如果用户可以授予自己自定义声明,那么它们将是一种无效的资源保护方法。

      您应该使用 Firebase Admin SDK 在您控制的后端分配自定义声明,并确保仅在您允许的特定情况下向用户授予声明 - 用户不应为自己分配自定义声明。

      【讨论】:

      • 实际上,我想使用自定义声明键值对来避免处理 Firebase DB,因为我必须将一些键值对保存到FirebaseUser。这对我的用例很方便 - Firebase 身份验证对我来说是完美的,但我需要为每个用户再存储一个变量。
      • 我了解您的用例,但这是不可能的。
      猜你喜欢
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 2021-06-30
      • 2020-05-27
      • 1970-01-01
      • 2019-02-09
      相关资源
      最近更新 更多