简体   繁体   中英

Getting permission error when creating a Firestore document

I'm trying to securely create a Firestore document without requiring user authentication and have defined the following rule to do so:

      allow create: if request.resource.data.deviceid == resource.id;

According to what I've read from Google, this should allow the document to be created if the pending write includes a field called 'DeviceID' that matches the document ID, which is what I think I'm doing (I confirmed that androidID is identical to the document ID):

        data.put("DeviceID", androidID);
        mDevIDDocRef.set(data)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.d(TAG, "DocumentSnapshot successfully written!");
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                    public void onFailure(@NonNull Exception e) {
                    Log.w(TAG, "Error writing document", e);
                }
            });

However, the above fails with a permission exception. What am I doing wrong?

During the create rule evaluation, the resource does not exist yet, so you have to read its future value: request.resource.data.whatever
To access an automatically generated document id, you need to read it from the document path:

match /myCollection/{docId} {
    allow create: if request.resource.data.deviceid == docId;
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM