Joost Döbken
Joost Döbken

Reputation: 4017

Google Cloud authentication with JSON keyfile using cURL

I have a JSON key file for Google Cloud in the form of:

{
  "type": "service_account",
  "project_id": "###",
  "private_key_id": "###",
  "private_key": "-----BEGIN PRIVATE KEY-----\n
  ########################################
  \n-----END PRIVATE KEY-----\n",
  "client_email": "###@###.gserviceaccount.com",
  "client_id": "###",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/###.gserviceaccount.com"
}

I would like to get an access_token while using regular curl commands instead of the GCP Console or installing the gcloud tool.

I would expect something like:

curl \
--request POST \
--data-binary "@path/to/key.json" \
https://accounts.google.com/o/oauth2/token

Upvotes: 12

Views: 6414

Answers (2)

coolaj86
coolaj86

Reputation: 77034

curl is not enough

I don't think you're going to be able to do it with just curl, because I believe it requires JWT authentication - reading between the lines in the docs and the error messages I've gotten myself.

oauth2l: a lightweight-ish approach

They have oauth2l, which can generate the JWT from the service_account.json JWK (though it should also work with the one you have which uses a PEM or CRT instead).

Unfortunately, they don't have a direct download link, but it's not too hard to get:

Try this:

Install Go:

Then install oauth2l:

go install github.com/google/oauth2l@latest

Then generate a JWT API Token:

oauth2l fetch --jwt --json ./service_account.json https://www.googleapis.com/auth/cloud-platform

Back to curl

Then use curl to fetch the API you want:

token=$(oauth2l fetch --jwt --json ./service_account.json https://www.googleapis.com/auth/cloud-platform)

curl -X POST https://www.googleapis.com/dns/v1/projects/<project>/managedZones \
  -H "Authorization: Bearer $token"

It's not ideal, but I think that'll get you what you need with minimal abstraction.

Less abstraction still

I'll try to post back when I get this figured out. It's going to require some sort of tool, but I think it can be even lighter-weight than oauth2l.

Upvotes: 6

arainchi
arainchi

Reputation: 1492

Precompiled oauth2l binaries are available for download from oauth2l GitHub page:

macos Linux Windows

Upvotes: 1

Related Questions