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

FireStore REST API调用遇401未授权错误,如何解决?(Postman/Retrofit)

解决Firestore REST API 401未授权问题(Postman + Retrofit)

先搞懂为什么规则公开还会报错

Firestore的安全规则是用来控制数据访问权限的,但REST API本身要求你提供一个凭证来标识请求属于你的项目——哪怕规则允许所有人访问,服务器也需要知道这个请求关联哪个项目,所以直接裸请求肯定会返回401。


Postman里的快速解决步骤

  1. 确认你的安全规则已发布且生效
    先检查Firebase控制台的Firestore规则,确保是公开读写的,并且已经点击了「发布」按钮(草稿不会生效):

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if true;
        }
      }
    }
    
  2. 给请求URL添加API Key参数
    去Firebase控制台的「项目设置」→「常规」页面,找到「Web API密钥」(一串长字符串),然后把它作为查询参数拼在你的请求URL后面:

    https://firestore.googleapis.com/v1beta1/projects/myapp-ef511/databases/countries?key=你的WebAPI密钥
    

    把这个URL复制到Postman里再发送请求,应该就能正常获取数据了。


后续用Retrofit开发的处理方案

在Retrofit里,你只需要把API Key作为查询参数集成到接口定义中即可:

  1. 定义Firestore API接口

    import retrofit2.Call;
    import retrofit2.http.GET;
    import retrofit2.http.Path;
    import retrofit2.http.Query;
    
    public interface FirestoreService {
        // 对应你的请求路径,替换成实际的数据库ID和项目ID
        @GET("v1beta1/projects/{projectId}/databases/{databaseId}")
        Call<YourResponseModel> getCountriesData(
                @Path("projectId") String projectId,
                @Path("databaseId") String databaseId,
                @Query("key") String apiKey
        );
    }
    
  2. 初始化Retrofit并发起请求

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://firestore.googleapis.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    
    FirestoreService service = retrofit.create(FirestoreService.class);
    Call<YourResponseModel> call = service.getCountriesData(
            "myapp-ef511",
            "countries",
            "你的WebAPI密钥"
    );
    
    // 异步请求处理
    call.enqueue(new Callback<YourResponseModel>() {
        @Override
        public void onResponse(Call<YourResponseModel> call, Response<YourResponseModel> response) {
            if (response.isSuccessful()) {
                // 处理返回的数据
            }
        }
    
        @Override
        public void onFailure(Call<YourResponseModel> call, Throwable t) {
            // 处理请求失败
        }
    });
    

额外提示

如果之后你需要关闭公开规则,改为用户认证后才能访问,那就要把API Key换成用户的ID Token(通过Firebase Auth获取),但目前公开规则的场景下,API Key就足够满足需求了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:15:57