Home  Firebase   Anyone with ...

Anyone with firebase app api key and config details can access firestore data?

Anyone with Firebase API key and other configuration details can access firestore. But you can secure your Firestore database by implementing additional layers of protection. Here are some strategies to enhance security beyond basic Firebase Authentication and Security Rules:

1. Implement Custom Authentication and Claims

Use Firebase Authentication with custom claims to add roles and permissions to users. This way, you can control access to Firestore data based on user roles.

Setting Custom Claims

// On your server-side code (e.g., Cloud Functions)
const admin = require('firebase-admin');
admin.initializeApp();

const setCustomClaims = async (uid, claims) => {
  await admin.auth().setCustomUserClaims(uid, claims);
};

// Example usage: setting admin claim
setCustomClaims('user-uid', { admin: true });

Firestore Security Rules with Custom Claims

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow only users with the admin claim to read and write to the admin collection
    match /admin/{document=**} {
      allow read, write: if request.auth.token.admin == true;
    }

    // Allow authenticated users to read and write their own data
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

2. Use Backend Services for Sensitive Operations

Move sensitive operations to backend services such as Firebase Cloud Functions. This allows you to control access more securely and perform additional validations server-side.

Example Cloud Function

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.addUserData = functions.https.onCall(async (data, context) => {
  if (!context.auth) {
    throw new functions.https.HttpsError('unauthenticated', 'The function must be called while authenticated.');
  }

  const userId = context.auth.uid;
  const userData = data;

  try {
    await admin.firestore().collection('users').doc(userId).set(userData);
    return { success: true };
  } catch (error) {
    throw new functions.https.HttpsError('unknown', 'Failed to add user data', error);
  }
});

3. Restrict API Key Usage

Restrict the usage of your Firebase API key to specific referrer domains or IP addresses in the Google Cloud Console. This limits where the API key can be used.

Setting API Restrictions

  1. Go to the Google Cloud Console.
  2. Navigate to the "Credentials" section.
  3. Select your API key and click "Edit".
  4. Under "API restrictions", select the APIs you want to restrict.
  5. Under "Application restrictions", choose the restriction type (e.g., HTTP referrers, IP addresses).

4. Use Firestore Rules for Fine-Grained Access Control

Write comprehensive Firestore Security Rules to enforce fine-grained access control. Use conditions based on user properties, request parameters, and document fields.

Example Fine-Grained Rules

service cloud.firestore {
  match /databases/{database}/documents {
    match /projects/{projectId} {
      // Allow read access if the user is a member of the project
      allow read: if request.auth != null && request.auth.token.projects[projectId] == true;

      // Allow write access if the user is an admin of the project
      allow write: if request.auth != null && request.auth.token.projectRoles[projectId] == 'admin';
    }

    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

5. Regular Monitoring and Auditing

Regularly monitor and audit the usage of your Firestore database and Firebase project. Use Firebase's built-in tools and logs to track access patterns and detect any unusual activity.

Published on: Jul 12, 2024, 10:34 AM  
 

Comments

Add your comment