如何使自定义声明与Firebase数据库中存储的角色保持同步 [英] How do you keep your custom claims in sync with roles stored in Firebase database

查看:116
本文介绍了如何使自定义声明与Firebase数据库中存储的角色保持同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题来自

This question is lifted from a comment on another thread and I figued that it was a good question that yet didn't have any answer on SO.

我如何将auth中的用户链接到他们在数据库中的特定配置文件? (配置文件包含全名,用户类型等)

How would i link my users in auth, to their specific profiles in the database? (profile contains, full name, usertype, etc.)

问题的上下文是指将用户身份验证访问逻辑存储在数据库中和/或作为自定义声明的不同策略.以及如何保持这两个同步(用户角色的用户身份验证中是否有任何功能?). /p>

The context of the question is referring to the different strategies of storing user auth access logic in the database and/or as custom claims. And how do you maintain those two to be in sync (Is there any function in User Authentication for User Roles?).

推荐答案

必须使用admin SDK设置自定义声明,这已经暗示可以利用云功能来根据您的逻辑设置声明.

Custom claims must be set with the admin SDK, which already hints that cloud functions can be utilized to set claims according to your logic.

如果用户配置文件数据包含用户类型和角色,则可以创建触发器以更新用户对象.如果您将角色存储为数组,则可以实现这样的功能.

If the user profile data contains the user type and roles, you can create a trigger for updates on the user object. If you store your roles as an array you can implement a function like this.

functions.firestore.document('users/{uid}').onUpdate((change, context) => {
  const uid = context.params.uid;
  const userBefore = change.before.data();
  const userAfter = change.after.data();

  const hasDifferentNumberOfRoles = userBefore.roles.length !== userAfter.roles.length;
  const hasOtherRoles = userBefore.roles.some((role: string) => userAfter.roles.indexOf(role) === -1);

  if (hasDifferentNumberOfRoles || hasOtherRoles) {
    return admin.auth().setCustomUserClaims(uid, { appRoles: userAfter.roles});  
  }

  return null;
});

这可确保每次数据库中的用户角色更改时,您的自定义声明身份验证也将更改.

This ensures that every time the user roles in data base change, your custom claims auth will also change.

数组对于角色来说很方便,因为使用array-contains可以很容易地查询Firestore以查找具有某些角色的用户,还可以很容易地在

Arrays are convenient for roles since it's easy to query Firestore to find users with certain roles using array-contains and it's also easy to check roles in your database rules as a list.

service cloud.firestore {
  match /databases/{database}/documents {

    match /protected-content/{documentId} {
      allow read: if hasUserRole('admin');
      allow write: if hasUserRole('super-admin');
    }

    function hasUserRole(role) {
      return role in request.auth.token.appRoles;
    }
  }
}

关于在自定义声明的appRoles属性中存储角色的一个小注释是,如果您更改结构或想为用户替换所有角色,它可以方便地删除所有当前角色.

A small side-note about storing your roles in a appRoles attribute on the custom claims, is that it makes in conveniently easy to remove all current roles if you change your structure or want to replace all roles for a user.

这篇关于如何使自定义声明与Firebase数据库中存储的角色保持同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆