使用PHP版FirestoreClient库时如何发送Auth Bearer令牌等自定义请求头
解决方案
你可以通过自定义认证凭证类的方式,将你生成的身份令牌传入Firestore客户端,具体实现如下:
实现步骤
- 先实现一个符合谷歌认证接口规范的自定义令牌提供类,用来返回你提前生成的身份令牌
- 初始化FirestoreClient时,将自定义令牌类实例通过
credentials配置项传入即可
完整代码示例
use Google\Cloud\Firestore\FirestoreClient; use Google\Auth\FetchAuthTokenInterface; class CustomAuthTokenProvider implements FetchAuthTokenInterface { // 你提前生成的Firebase身份令牌 private string $customToken; // 令牌的实际过期时间戳 private int $expireTimestamp; public function __construct(string $customToken, int $expireTimestamp) { $this->customToken = $customToken; $this->expireTimestamp = $expireTimestamp; } public function fetchAuthToken(callable $httpHandler = null) { return [ 'access_token' => $this->customToken, 'expires_at' => $this->expireTimestamp ]; } public function getCacheKey() { return ''; } public function getLastReceivedToken() { return null; } } // 业务代码 $id = 123; $data = ['message' => 123]; // 替换为你实际生成的令牌和对应的过期时间戳 $yourCustomToken = 'xxx.xxx.xxx'; $tokenExpireAt = time() + 3600; $db = new FirestoreClient([ 'projectId' => 'myProject', 'credentials' => new CustomAuthTokenProvider($yourCustomToken, $tokenExpireAt) ]); $db->collection('messages')->document($id)->create($data);
注意事项
- 你生成的身份令牌需要符合Firebase JWT规范,包含必要的用户标识、权限声明信息
- 安全规则中可以直接通过
request.auth读取令牌携带的用户信息,校验逻辑和前端传递令牌时完全一致 - 如果令牌过期需要重新生成新的令牌实例传入客户端,无需重启服务
内容的提问来源于stack exchange,提问作者Ask17
相关产品推荐
相关产品推荐

