You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用密钥访问Firebase Firestore并配置安全读写规则

Firestore 基于应用密钥的安全规则配置

核心安全提醒

绝对不能在客户端代码中硬编码密钥,也不要直接在Firestore规则里明文存储密钥(方案二仅作演示,强烈不推荐),否则密钥极易被泄露,导致数据库完全暴露。优先采用自定义身份验证方案,通过后端管控密钥,避免直接暴露。


方案一:自定义身份验证(安全推荐)

通过后端验证应用密钥,为客户端生成Firebase自定义认证Token,客户端用Token登录后,Firestore规则验证用户的自定义声明。

1. 后端生成自定义Token

用Firebase Admin SDK在后端实现密钥验证和Token生成,密钥存储在后端环境变量中,不对外暴露。示例(Node.js):

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

// 合法密钥从环境变量读取
const VALID_APP_KEY = process.env.YOUR_APP_SECRET_KEY;

// 提供给客户端的接口,验证密钥后返回Token
async function getCustomToken(req, res) {
  const { appKey } = req.body;
  if (appKey !== VALID_APP_KEY) {
    return res.status(403).send('Invalid app key');
  }
  // 生成带自定义声明的Token,UID可根据客户端标识自定义
  const token = await admin.auth().createCustomToken('app-client-uid', {
    isAuthenticated: true
  });
  res.send({ token });
}

2. 客户端登录并访问Firestore

客户端先请求后端接口获取Token,再用Firebase Auth登录,之后即可合法访问数据库:

import { getAuth, signInWithCustomToken } from "firebase/auth";
import { getFirestore, doc, getDoc } from "firebase/firestore";

const auth = getAuth();
const db = getFirestore();

// 从后端获取Token
async function loginWithAppKey(appKey) {
  const response = await fetch('/api/get-custom-token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ appKey })
  });
  const { token } = await response.json();
  // 登录Firebase Auth
  await signInWithCustomToken(auth, token);
}

// 登录后访问数据
async function fetchData() {
  await loginWithAppKey('你的应用密钥');
  const docRef = doc(db, 'your-collection', 'your-doc');
  const docSnap = await getDoc(docRef);
  console.log(docSnap.data());
}

3. 更新Firestore规则

规则中验证用户已登录且带有合法的自定义声明:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null && request.auth.token.isAuthenticated == true;
    }
  }
}

方案二:直接在规则中验证请求密钥(不推荐)

此方式将密钥直接通过请求传递并在规则中验证,密钥极易被抓包或从客户端代码提取,仅作特殊场景演示:

1. 客户端请求时携带密钥

以Web端为例,在请求元数据中添加密钥:

import { getFirestore, doc, getDoc } from "firebase/firestore";

const db = getFirestore();
const docRef = doc(db, 'your-collection', 'your-doc');

// 请求时携带密钥(Web端通过metadata传递)
const docSnap = await getDoc(docRef, {
  metadata: { appKey: '你的应用密钥' }
});

2. 更新Firestore规则

规则中验证请求元数据的密钥是否匹配(注意:密钥会明文暴露在规则中):

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // 明文存储密钥,风险极高!
    let VALID_KEY = "your-secret-app-key";
    match /{document=**} {
      allow read, write: if request.resource.metadata.appKey == VALID_KEY;
    }
  }
}

内容的提问来源于stack exchange,提问作者Andrei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 23:41:11