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

如何用PHP将Firebase Firestore从测试模式转为生产模式并解决认证问题

解决方案:用用户认证令牌替代服务账号访问Firestore

你的权限错误根源在于服务账号默认以管理员身份访问,此时request.auth为null,而你的安全规则要求大部分集合需request.auth != null,因此触发权限限制。以下是两种可行的修改方案:


方案1:使用用户ID令牌认证(推荐,符合应用级认证逻辑)

放弃服务账号密钥,改用Firebase Auth生成的用户ID令牌初始化Firestore客户端,这样请求会携带用户认证信息,满足request.auth != null的规则要求。

修改后的PHP代码

假设你已从前端获取用户登录后的ID令牌(或后端自行生成):

public function __construct(string $idToken) {
    $this->firestore = new FirestoreClient([
        'projectId' => 'test-4c1ff',
        'authToken' => $idToken // 替换为用户的ID令牌
    ]);
}

后端生成ID令牌的方法(若需要)

如果后端需要自行创建用户并获取令牌,可通过Firebase Auth API实现:

use Kreait\Firebase\Factory;
use GuzzleHttp\Client;

// 初始化Firebase工厂
$factory = (new Factory)->withProjectId('test-4c1ff');
$auth = $factory->createAuth();

// 创建用户(若已有用户,直接调用$auth->getUser('uid')获取)
$user = $auth->createUser([
    'email' => 'your-user@example.com',
    'password' => 'secure-password'
]);

// 生成自定义令牌
$customToken = $auth->createCustomToken($user->uid);

// 交换为ID令牌(通过Firebase Auth REST API)
$client = new Client();
$response = $client->post('https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken', [
    'query' => ['key' => '你的Firebase Web API密钥'], // 在Firebase控制台-项目设置-通用中获取
    'json' => [
        'token' => $customToken,
        'returnSecureToken' => true
    ]
]);

$idToken = json_decode($response->getBody(), true)['idToken'];

// 用ID令牌初始化Firestore
$this->firestore = new FirestoreClient([
    'projectId' => 'test-4c1ff',
    'authToken' => $idToken
]);

方案2:服务账号模拟用户访问

若必须保留服务账号,可通过模拟特定用户身份访问Firestore,让request.auth被正确填充:

use Kreait\Firebase\Factory;

public function __construct() {
    global $key;
    $factory = (new Factory)->withServiceAccount($key)->withProjectId('test-4c1ff');
    
    // 获取要模拟的用户(替换为你的目标用户UID)
    $auth = $factory->createAuth();
    $user = $auth->getUser('target-user-uid');
    
    // 初始化带用户身份的Firestore客户端
    $this->firestore = $factory->createFirestore()->withAuth($user);
}

规则匹配说明

  • 对于/projects集合,你的规则允许无认证访问,两种方案都能正常读写;
  • 其他集合需request.auth != null,方案1的ID令牌或方案2的模拟用户都会填充request.auth,满足规则要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:45:33