如何在 Firebase Auth 中设置角色?

11

我目前使用电子邮件和密码登录。但我希望能够为每个用户分配角色:管理员或用户。我已经阅读到可以通过使用自定义认证方法来实现,但我发现文档对于如何在电子邮件/密码认证中实现不够清晰。

我目前正在使用firebase为ember emberfire

更新:

文档参考:https://www.firebase.com/docs/web/guide/login/custom.html


请添加您参考的文档链接,不确定是Ember还是Ember-Fire或Firebase..谢谢! - TameBadger
@TameBadger添加了它。 - FutoRicky
如何实现取决于您。自定义安全提供程序是一种方式,但以下是使用任何提供程序的示例:https://gist.github.com/sararob/331760829a9dcb4be3e7。另请参阅这个2.5年前的答案,它仍然非常相关:https://dev59.com/BWIk5IYBdhLWcg3wKLad - Frank van Puffelen
这些可能也是良好的起点: https://www.google.com/search?q=site:stackoverflow.com+firebase+role+based+security - Frank van Puffelen
@FrankvanPuffelen 但是我应该在哪里设置这个数据结构呢?所有这些答案都感觉不完整。 - FutoRicky
如果有人有更完整的工作示例/教程可供使用,我很想看看。否则,所有这些都是一个很好的开始,使您的探索变得更加可行。 - Frank van Puffelen
1个回答

12
Firebase刚刚推出了通过ID令牌上的自定义用户声明为任何用户提供基于角色的访问权限的支持:https://firebase.google.com/docs/auth/admin/custom-claims 您可以定义管理员访问规则:
{
  "rules": {
    "adminContent": {
      ".read": "auth.token.admin === true",
      ".write": "auth.token.admin === true",
    }
  }
}

使用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.
});

这将传播到相应用户的ID令牌声明中。
要从客户端的令牌解析它,请检查:https://firebase.google.com/docs/auth/admin/custom-claims#access_custom_claims_on_the_client

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接