Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestorefirebase-security

How to add additional parameter to request object for consuming in Firebase security rules


I want non-authenticated users to get documents from firebase with a secureKey. What I want to achieve is adding additional variable to request, and check it on the rules if it is a valid request. For example:

const q = query(doc(db, "questions/question_uid"));
const questionDoc = await getDoc(q, {secureKey: "123456"});

In rules side:

match /questions/{uid} {
  allow get: if request.secureKey === "123456";    
}

I assume that the user is not authenticated, but has the valid secureKey. (Above code is not a valid code, I wrote it just for the explanation.) Is it possible to add custom parameters to requests and receive them on the rules side?

Adding parameters to getDoc is not valid like this:

const questionDoc = await getDoc(q, {secureKey: "123456"});

Solution

  • Is it possible to add custom parameters to requests and receive them on the rules side?

    Adding an additional variable to the request and check it in the security rules is not possible, but you can implement something similar with Custom Claims. However, for that to work, you would need to have an account for each user.

    (You can) define custom attributes on user accounts. This provides the ability to implement various access control strategies, including role-based access control, in Firebase apps. These custom attributes can give users different levels of access (roles), which are enforced in an application's security rules.

    In the security rules you can check if the user has the claim, like the following example:

    allow read: if request.auth.uid != null && request.auth.token.secureKey == "123456";