2
votes

Firebase security rules dose not recognize request.auth.token.name

I want to apply security rules using user's display name. I used signInAnonymously and updateProfile.

This is my Client code

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) })
  })
})

This is my Firestore security rule

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";
    }
  }
}

I expected 'Success', but actual output is

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)
2
shoudn't request.auth.token.name be request.auth.token.displayName ?Abdelillah Aissani
@Dadboz request.auth.token.name is right way to retrieve requester's displayName firebase API docfre bern
Since displayName is a custom field which you're setting in the token, you cannot access it via name. So try the solution mentioned by @Dadboz above.denniskbijo
Did you solve this, I'm also stuck with it?RJB
Does anyone solve this probem? I'm also stuck...Keisuke Nagakawa 永川 圭介

2 Answers

0
votes

I couldn't directly solved this problem but I bypassed the problem by making it authencate by UserID instead of User name as follows:

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

Please note that your query making HelloCollection should also be changed so as to store user id with texts.

0
votes

Here's a working example..

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

@fre bern is right. You can access user's display name by "request.auth.token.name" .. if u cant get it to work.. mb sth else is wrong with your code