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

使用Go SDK读取Firestore时遭遇PermissionDenied错误排查

Firestore Go SDK 权限拒绝问题排查

已配置的Firestore安全规则

为开发环境设置了全读写权限的规则:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

Curl请求验证成功

通过Curl命令可正常获取目标文档:

curl -X GET "https://firestore.googleapis.com/v1beta1/projects/<my-project-id>/databases/(default)/documents/configurations/test"

返回结果:

{
  "name": "projects/<my-project-id>/databases/(default)/documents/configurations/test",
  "fields": {
    "hello": {
      "stringValue": "world"
    }
  },
  "createTime": "2023-10-04T17:23:41.476045Z",
  "updateTime": "2023-10-04T17:23:41.476045Z"
}

Go SDK读取代码

使用以下Go代码尝试读取文档:

// Firestore test
func readFromFirestore(){

    ctx := context.Background()
    client, err := firestore.NewClient(ctx, os.Getenv("PROJECT_ID"))
    if err != nil {
        log.Fatal("Error creating firestore client: ", err)
    }
    log.Println("Firestore client: ", client)
    // Creating the documentref
    docref := client.Doc("configurations/test")
    fmt.Println("Document ref: ", docref)
    docsnap, err := docref.Get(ctx)
    if err != nil {
        log.Fatal("Error reading document: ", err)
    }
    dataMap := docsnap.Data()
    fmt.Println(dataMap)
}

错误输出

运行代码后返回权限拒绝错误:

go run .                                                                               
2023/10/04 14:33:15 Firestore client:  &{0xc00011d590 <my-projectid> (default) 0xc00011d5a8}
Document ref:  &{0xc0002c8160 projects/<my-project-id>/databases/(default)/documents/configurations/test configurations/test test 0xc00011d5f0}
2023/10/04 14:33:16 Error reading document: rpc error: code = PermissionDenied desc = Missing or insufficient permissions.
exit status 1

排查方向

  • 本地认证凭据问题:Go SDK默认读取GOOGLE_APPLICATION_CREDENTIALS环境变量指向的服务账号密钥,检查该变量是否正确设置,或显式指定凭据路径初始化客户端:
    opts := option.WithCredentialsFile("/path/to/service-account-key.json")
    client, err := firestore.NewClient(ctx, os.Getenv("PROJECT_ID"), opts)
    
  • 项目ID匹配问题:确认os.Getenv("PROJECT_ID")获取的项目ID与Curl请求中的<my-project-id>完全一致,避免拼写或大小写错误。
  • 客户端初始化细节:尝试显式指定数据库ID初始化客户端,排除默认配置异常:
    client, err := firestore.NewClientWithDatabase(ctx, os.Getenv("PROJECT_ID"), "(default)")
    
  • 服务账号权限验证:即使安全规则开放,服务账号需拥有Cloud Datastore User或Firestore Editor等角色,前往Google Cloud控制台IAM页面检查权限配置。
  • 网络代理问题:本地代理可能干扰SDK的认证请求,尝试关闭代理或在客户端初始化时配置代理选项。

内容的提问来源于stack exchange,提问作者André Luiz Tiago Soares

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:44:54