Home > Net >  Firestore REST API make authenticated request with http-client
Firestore REST API make authenticated request with http-client

Time:11-24

I want to get data from a firestore via the REST API. I'm using an HTTP-Client (Webstorm) and do the following.

First I authenticate with Google which works fine and does return a token:

POST https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=<firebase-api-key>
Accept: application/json
Content-Type: application/json

{
  "email": "[email protected]",
  "password": "notthispassword"
}

But then, trying to get data from the firestore (not realtime-db) like this

GET https://firestore.googleapis.com/v1/projects/<projectId>/databases/(default)/documents/<collection>
Accept: application/json
Authorization: Bearer <token from auth response>

it keeps telling me:

{
    "error": {
        "code": 401,
        "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "status": "UNAUTHENTICATED"
    }
}

These are my firestore security rules:

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

I would be happy if somebody could tell me where I am going wrong here.

CodePudding user response:

The first part of the solution was to read the response carefully. It containes the following link https://developers.google.com/identity/sign-in/web/devconsole-project.

Then I had to understand that if you are using the google-identitiy-toolkit you kind of left the firebase-realm and must append the api-key generated in the GC-console (not the firebase-key!) (https://console.cloud.google.com/apis/credentials) to the URL used to fetch the data like this:

GET https://firestore.googleapis.com/v1/projects/<projectId>/databases/(default)/documents/<collection>?key=<google-cloud-api-key>
Accept: application/json 
Authorization: Bearer <token from auth response>
  • Related