Firestore 安全规则无法检索 request.auth.token.name



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

我想使用用户的显示名称应用安全规则。我使用了 signInAnonymly 和 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)

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

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

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

这是一个工作示例。

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

@fre伯尔尼是对的。您可以通过"request.auth.token.name"访问用户的显示名称。如果你不能让它工作..MB sth 否则你的代码有问题

最新更新