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

Firebase未认证用户访问排行榜的最优实现方案咨询

Firebase未认证用户访问排行榜的实现方案

1. 调整Firebase安全规则

当前规则限制了未认证用户的读取权限,需要修改规则,允许通过App Check验证的未认证用户只读访问,同时保留原有的写入权限逻辑:

match /users/{userId} {
  allow update: if request.auth != null && request.auth.uid == userId;
  allow delete: if false;
  allow create: if request.auth != null;
  // 允许认证用户读取,或通过App Check的未认证用户读取
  allow read: if (request.auth != null) || (request.app != null);
}

如果用户资料包含敏感字段(如邮箱、手机号),可以进一步限制未认证用户只能读取排行榜所需的字段(比如总得分、用户名),提升安全性:

match /users/{userId} {
  allow update: if request.auth != null && request.auth.uid == userId;
  allow delete: if false;
  allow create: if request.auth != null;
  allow read: if 
    (request.auth != null) || 
    (request.app != null && request.resource.data.keys().hasOnly(["totalScore", "username"]));
}

2. 实现排行榜查询逻辑

在应用中编写Firestore查询,按用户总得分降序排列,取前10条数据即可生成排行榜。以下是Web端的示例代码:

import { collection, query, orderBy, limit, getDocs } from "firebase/firestore";
import { db } from "./firebase-config";

// 获取前10名排行榜数据
async function fetchTop10Leaderboard() {
  const leaderboardQuery = query(
    collection(db, "users"),
    orderBy("totalScore", "desc"),
    limit(10)
  );
  
  const querySnapshot = await getDocs(leaderboardQuery);
  const leaderboardData = [];
  
  querySnapshot.forEach(doc => {
    leaderboardData.push({
      userId: doc.id,
      username: doc.data().username,
      totalScore: doc.data().totalScore
    });
  });
  
  return leaderboardData;
}

3. 启用并配置Firebase App Check

既然你计划使用App Check,需要确保在Firebase控制台完成以下配置:

  • 为对应平台(Web/iOS/Android)启用App Check
  • 集成App Check SDK到你的应用中,确保所有Firestore请求都经过App Check验证
  • 这样request.app != null的规则条件才会生效,拦截未通过验证的非法请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:32:21