【问题标题】:AngularFire hasCustomClaim and customClaims not workingAngularFire hasCustomClaim 和 customClaims 不起作用
【发布时间】:2021-10-23 22:52:00
【问题描述】:

我一直在尝试使用 Firebase 自定义声明,并成功地创建了基于用户的角色,例如 manager, editor, admin。这就是我在 Firebase Emulator Suite 中保存自定义声明的方式。

对于用户自定义 clams 设置如下 {"role": "manager"},但每当我尝试登录并获取用户的自定义声明时,它都不起作用。

仅供参考,我也尝试设置这样的自定义声明{"manager": true},但如果我在if and else 条件下使用它,hasCustomClaim("manager") 总是有效,即使我设置了{"manager": false},如果我尝试使用管理员权限登录,但经理级别仍然正常工作

const adminOnly = () => hasCustomClaim("admin");
const editorOnly = () => hasCustomClaim("editor");
const managerOnly = () => hasCustomClaim("manager" ); 

const editorOnly2d = pipe(customClaims, map(claims => claims.role == "editor"));
const mngOnly2 = pipe(customClaims, map(claims => claims.role == "manager"));

如何获取当前登录的用户自定义声明,以便我可以根据用户角色设置路由?

这是我登录后得到的authUser.getIdTokenResult(true)

aud: "testing" 
auth_time: 1629796111 
email: "test12@gmail.com" 
email_verified:false 
exp: 1629799711 
firebase: {identities: {…}, sign_in_provider: "password"} 
iat: 1629796111 
iss: "https://securetoken.google.com/testing" 
role: "manager" 
name: "Testing" 
sub: "ZUlXd59HMhFI5gyozxW1xw0IXtPi" 
user_id: "ZUlXd59HMhFI5gyozxW1xw0IXtPi"

我试图搜索这个问题,但他们都建议我上面使用的相同内容。

【问题讨论】:

  • 自定义声明是 Firebase 身份验证的一项功能,而不是 Firestore 的一项功能。我已为您解决了这个问题,但对于未来的问题,请记住这一点。通过正确标记和标记您的问题,具有正确知识的人更有可能找到它。

标签: javascript angular google-cloud-firestore firebase-authentication angularfire2


【解决方案1】:

{"role": "manager"} 将不起作用,因为hasCustomClaim("admin")(据我所知)仅检查是否存在 命名admin 的声明。

这也解释了为什么它在您使用 "manager": false 时起作用,hasCustomClaim 仅检查声明是否存在,而不管其价值如何。非管理员不应拥有admin 声明。

因此,如果您想使用现有的 AngularFire 管道,您需要声明用户是否是 admineditor 和/或 manager

如果您想使用自己的基于角色的访问控制,这也是可能的,但您必须实现自己的身份验证管道过滤器。对于这些,您首先要记录 claims,这样您就可以看到 map 呼叫正在处理的问题。

【讨论】:

  • 您好,坦率地感谢您的回复,这也是我的想法,但在调试时我想它可能会检查是否存在,所以我尝试了这个if(adminOnly){ console.log('You are admin') }else{ console.log('not admin')} if(managerOnly){ console.log('you are a manager') }else{ console.log('not a manager')},但在这两种情况下我都得到了'You are admin' 和@987654334 @ 同时。所以我认为登录时我需要使用 authUser.getIdTokenResult(true) 并获得自定义声明
  • 抱歉,我不确定你的意思。您能否在您的问题中显示用户现有 ID 令牌的 console.log()(因此无需强制刷新)?如果role 声明还没有出现,那么代码不起作用是有道理的。请注意,声明从服务器传播到客户端最多需要一个小时,因为客户端每小时只刷新一次 ID 令牌(除非您在代码中强制刷新)。
  • 您好,用户角色已经存在,请查看aud: "testing" auth_time: 1629796111 email: "test12@gmail.com" email_verified: false exp: 1629799711 firebase: {identities: {…}, sign_in_provider: "password"} iat: 1629796111 iss: "https://securetoken.google.com/testing" manager: true name: "Testing" sub: "ZUlXd59HMhFI5gyozxW1xw0IXtPi" user_id: "ZUlXd59HMhFI5gyozxW1xw0IXtPi"
  • 请编辑您的问题以包含该信息,因为在这样的评论中快速浏览变得非常困难。但是:我没有在其中看到 role 声明,这可以解释为什么您的自定义过滤器在检查 claims.role == "editor" 时不起作用。
猜你喜欢
  • 1970-01-01
  • 2020-07-27
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多