Shadow
Shadow

Reputation: 105

Flutter firebase send Token with database read

When I try to read a document in my firebase, I want to be able to check, if the request is legit. For this reason, there is a token that is stored in the firebase. I only want to allow the access, if the token matches with the clients. So my security rules should check, if the token from the client is matching the one in the document. I can not do this with auth, as my App does not have a login and relies purely on the document id and token to access the data.

enter image description here

So my question is, how can I send a parameter with my flutter read request ? And how can I compare, if the token that is in the request matches the one in the document. I figured this would be roughly the way:

match /databases/{database}/documents {
  match /test/{document} {
    allow write, read: if request.resource.data.token== document.data.token;
  }
}

Upvotes: 1

Views: 760

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

So my question is, how can I send a parameter with my flutter read request?

You can't pass your own parameters to the security rules. The only information available in the security rules (for a read request) is:

  • the token of the user that made the request.
  • the path of the data that the user is trying to read.
  • any query parameters they pass along.

So if you want to do this type of check, you'll have to encode the token in one of those three things. The simplest one is to use the token as the document ID. And then change your rules to:

match /databases/{database}/documents {
  match /test/{document} {
    allow get: if true;
  }
}

The user can now still get a document, but can no longer list documents (read is he same as get + list). That boils down to: if you know the ID of a document, you can read it. This is a quite common way to secure document access, and is known as a form of a shared secrete.

Upvotes: 2

Related Questions