Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 821
Joost Döbken Avatar asked Mar 21 '19 14:03

Joost Döbken


1 Answers

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.

  • https://cloud.google.com/service-usage/docs/getting-started#api

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:

  • See https://webinstall.dev/golang (easy) or https://golang.org/dl (a good read)

Then install oauth2l:

go get github.com/google/oauth2l
go install github.com/google/oauth2l

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.

like image 77
coolaj86 Avatar answered Nov 04 '22 00:11

coolaj86