【问题标题】:Firestore security rules can't retrieve request.auth.token.nameFirestore 安全规则无法检索 request.auth.token.name
【发布时间】:2019-12-02 07:30:51
【问题描述】:

Firebase 安全规则无法识别 request.auth.token.name

我想使用用户的显示名称应用安全规则。 我使用了 signInAnonymously 和 updateProfile。

这是我的客户代码

var firebase = require('firebase/app')
require('firebase/auth')
require('firebase/firestore')

firebase.initializeApp(~~~)
firebase.auth().signInAnonymously().then(({user}) => {
  user.updateProfile({
    displayName: 'ABC',
  }).then(() => {
    // {..., uid: '~~~', displayName: 'ABC', photoURL: null}
    console.log(user.toJSON()) 

    var db = firebase.firestore()
    db.collection('HelloCollection').doc('WorldDoc').get()
      .then((doc) => { console.log('Success') })
      .then((err) => { console.log('Failed', err) })
  })
})

这是我的 Firestore 安全规则

service cloud.firestore {
  match /databases/{database}/documents {
    match /HelloCollection/{docId} {
      // allow read, create, update: if true; // This evaluated true.
      // This evaluated false.
      allow read, create, update: if request.auth.token.name == "ABC";
    }
  }
}

我期待“成功”, 但实际输出是

Failed FirebaseError: Missing or insufficient permissions.
    at new FirestoreError (webpack-internal:///3120:352:28)
    at JsonProtoSerializer.fromRpcStatus (webpack-internal:///3120:14802:16)
    at JsonProtoSerializer.fromWatchChange (webpack-internal:///3120:15293:44)
    at PersistentListenStream.onMessage (webpack-internal:///3120:11280:43)
    at eval (webpack-internal:///3120:11209:30)
    at eval (webpack-internal:///3120:11249:28)
    at eval (webpack-internal:///3120:1630:20)
    at run (webpack-internal:///1421:66:22)
    at eval (webpack-internal:///1421:79:30)
    at MutationObserver.flush (webpack-internal:///358:18:9)

【问题讨论】:

  • 不应该 request.auth.token.namerequest.auth.token.displayName 吗?
  • @Dadboz request.auth.token.name 是检索请求者的 displayName firebase API doc 的正确方法
  • 由于 displayName 是您在令牌中设置的自定义字段,因此您无法通过名称访问它。所以试试上面@Dadboz 提到的解决方案。
  • 你解决了吗,我也卡住了?
  • 有人解决这个问题吗?我也卡住了……

标签: javascript firebase google-cloud-firestore firebase-authentication firebase-security


【解决方案1】:

我无法直接解决这个问题,但我绕过了这个问题,通过 UserID 而不是用户名进行身份验证,如下所示:

request.resource.data.uid == request.auth.token.sub

请注意,您的 HelloCollection 查询也应更改,以便将用户 ID 与文本一起存储。

【讨论】:

    【解决方案2】:

    这是一个工作示例..

    match /stuff/{candy} {
      allow read, write: if request.auth.token.name == candy
    }
    

    @fre bern 是对的。您可以通过“request.auth.token.name”访问用户的显示名称..如果你不能让它工作.. mb sth else is wrong with your code

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 2022-12-11
      • 2018-10-19
      • 2019-07-05
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多