How to properly authorize request to Google Cloud Storage API? - google-cloud-storage

I am trying to use the Google Cloud Storage JSON API to retrieve files from a bucket using http calls.
I am curling from a Container in GCE within the same project as the storage bucket, and the service account has read access to the bucket
Here is the pattern of the requests:
https://storage.googleapis.com/{bucket}/{object}
According to the API console, I don't need anything particular as the service account provides Application Default Credentials. However, I keep having this:
Anonymous caller does not have storage.objects.get
I also tried to create an API key for the project and appended it to the url (https://storage.googleapis.com/{bucket}/{object}?key={key})but I still got the same 401 error.
How can I authorize requests to query this API?

The URL that you are using is not correct. The APIs use a URL that starts with https://www.googleapis.com/storage/v1/b.
Using API keys is not recommended. Instead you should use a Bearer: token. I will show both methods.
To get an access token for the gcloud default configuration:
gcloud auth print-access-token
Then use the token in your curl request. Replace TOKEN with the token from the gcloud command.
To list buckets:
curl -s -H "Authorization: Bearer TOKEN" https://www.googleapis.com/storage/v1/b
curl https://www.googleapis.com/storage/v1/b?key=APIKEY
To list objects:
curl -s -H "Authorization: Bearer TOKEN" https://www.googleapis.com/storage/v1/b/examplebucket/o
curl https://www.googleapis.com/storage/v1/b/examplebucket/o?key=APIKEY
API Reference: List Buckets

If you are able to create another cluster you can obtain permission like this:
Click in "avanced edit"
next click in "Allow full access to all Cloud APIs"
And that's it :D

Related

REST API URL that can be used to retrieve the metadata for a resource contained in a storage bucket

I am new to Cloud and I've been practising it for a while. I have a use case.
I want to retrieve the metadata of images in the bucket through a suitable REST API. I searched in API explorer and found Cloud Resource Manager API that could help retrieve the metadata but after exploring it I couldn't figure out the link.
API Required Fields
Can someone help me to understand what to put in the parent field?
You are using the wrong REST API.
The REST API endpoint is:
https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME
To view metadata, here is an example using the REST API in curl:
gcloud auth application-default login
BUCKET=BUCKET_NAME
OBJECT=OBJECT_NAME
URL=https://storage.googleapis.com/storage/v1/b/$BUCKET/o/$OBJECT
TOKEN=$(gcloud auth application-default print-access-token)
curl -v -X GET -H "Authorization: Bearer $TOKEN" $URL

How do I set up a Google Cloud Function with Authentication?

Disclaimer: I'm completely new to Google Cloud Functions and serverless functions in general.
I've set up a basic Google Cloud Function, set it to HTTPS trigger and Require Authentication, and given the service account and my account the cloud function invoker role.
However, whenever I use Postman to sent an HTTP request to the function using my oauth2 token, I get a 401 Unauthorized error.
I've also followed the steps here: https://cloud.google.com/functions/docs/securing/authenticating
to create and download the service account key and make an HTTP request using cURL and get the same error.
How do I need to set this up so that authorized users can send HTTP requests to this function?
Here's what I'm doing:
$gcloud auth login (to log in with my account with cloud invoker permission)
$curl https://my-trigger-url \ -H "Authorization: bearer $(gcloud auth print-identity-token)"
Guillaume found the solution:
My cURL syntax to trigger the Cloud Function needed the -H "Authorization: bearer $(gcloud auth print-identity-token)" before the URL instead of after, which is the opposite of Google's own documentation.
Thanks for your help.

How to auto generate new Bearer Token in Postman for GCP Storage

I am trying to upload file from local to GCP bucket through cloud storage Rest API (https://storage.googleapis.com/upload/storage/v1/b) using Postman.
I am using Bearer Token for authorization and running $(gcloud auth print-access-token) command on GCP Shell to generate that token every time.
I need to know, how to auto generate that token from Postman while sending request ?
Is there any way to execute $(gcloud auth print-access-token) every time as a Pre-request Script within Postman ?
Thanks
I'm not very good with postman, but I think you can run pre-request to get token and reuse it in the subsequent request.
If so, you can get inspiration from the gcloud auth print-access-token command by adding the --log-http param to visualize the request performed by the CLI and to reproduce them in Postman.
EDIT 1
If you perform the request, you can see that a post is performed to this URL https://oauth2.googleapis.com/token
To reproduce the call, you can try with a curl
curl -X POST -d "grant_type=refresh_token&client_id=32555940559.apps.googleusercontent.com&client_secret=ZmssLNjJy2998hD4CTg2ejr2&refresh_token=<REFRESH_TOKEN>&scope=openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.admin+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcompute+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Faccounts.reauth" https://oauth2.googleapis.com/token
In this call, you need your REFRESH_TOKEN, that you can get here
cat ~/.config/gcloud/legacy_credentials/<YOUR EMAIL>/adc.json
Google Cloud Storage requires authentication as other Google APIs and one of the authentication way is providing bearer token. These bearer tokens are short lived and require regeneration.
So there are 3 ways to generate bearer tokens so you can interact with Google Storage API or other Google APIs using Postman:
Using oauth2l CLI ( Manual Regeneration of new bearer token and update of Authorization header with the new token)
This oauth2l CLI utility allows you to generate bearer tokens which can be pasted into the Authorization header in postman. You can use
Configuration of Postman with OAuth 2 and User Credentials ( Tokens can be managed via the Postman UI and expired ones cleaned up at the click of a button)
Postman can be configured to trigger the OAuth 2 flow and use a generated bearer token in all of the requests. But please make sure that all users have the correct permissions in the Google Cloud Platform project.
You will need to create OAuth 2 credentials in Google Cloud Console:
Go to APIS and Services
Then go to Credentials tab
Click on Create Credentials
Select OAuth Client ID
Fill the fields to create OAuth Client ID ( also add an Authorized redirect URI however this doesn’t need to resolve to anywhere).
The Client ID and Client Secret need to be saved in your machine.
Use Postman’s environment variable functionality to use different credentials per environment/project. In Postman create a new environment for your credentials using the cog icon at the top right.
Configure the variables accordingly: AUTH_CALLBACK_URL , AUTH_URL, AUTH_CLIENT_ID, AUTH_CLIENT_SECRET, AUTH_ACCESS_TOKEN_URL
This variable should be identical to that defined in the OAuth 2 Client ID creation menu and should be one of the following : AUTH_SCOPE
Once defined, these variables can be used in your Authorization tab in Postman. This can be configured at the collection level, the folder level or even the individual request level.
To Regenerate the Token, you can go to Authorization Tab and click on GET NEW ACCESS TOKEN
Configuration of Postman to use a pre-request script and service credentials (The pre-request script automatically regenerates the bearer token when it expires)
For this please check this Tutorial to follow the steps provided there.

How to obtain the authorization code required for User Credentials through the cURL's command line

I trying to use GCS "User Credentials" to connect to Google cloud storage using libcurl library.
"User Credentials" authentication needs Client Id & Secret key to connect to GCS, but in this process Authentication Code also needs to be generated.
I need to generate this Authentication code using cURL.
Can anyone help me ??
The Client ID you mentioned is the same as the Authentication ID and can only be generated from either the Cloud Console's Credentials Page or via the OAuth 2.0 Playground.
If you are trying to generate an Access Token (OAUTH2_TOKEN), you will need to complete an authentication flow to authorize requests as a user. Cloud Storage uses OAuth 2.0 for API authentication and authorization.
Here's what you need to do to get an authorization access token from the OAuth 2.0 Playground:
Select & authorize APIs (Cloud Storage)
Select the scope for the APIs you would like to access or input your own OAuth scopes, e.g.: https://www.googleapis.com/auth/devstorage.read_write
Then click the "Authorize APIs" button
Once you've got the Authorization Code click the "Exchange authorization code for tokens" button, you will get a refresh and an access token which is required to access OAuth protected resources.
Grab the Access Token to use in your cURL command
Then configure your request to Cloud Storage API by constructing your HTTP request like so (upload):
curl -X POST --data-binary #[OBJECT_LOCATION] \
-H "Authorization: Bearer [OAUTH2_TOKEN]" \
-H "Content-Type: [OBJECT_CONTENT_TYPE]" \
"https://www.googleapis.com/upload/storage/v1/b/[BUCKET_NAME]/o?uploadType=media&name=[OBJECT_NAME]"
You can have a look at this Cloud Storage upload example in our public docs to guide you with constructing a request and testing it out.
Hope this helps.

How to authenticate against Kubernetes clusters running on Google Container Engine using REST API?

I'm writing an application to monitor a kubernetes cluster running on Google Container Engine. On the host where my application deployed, there are no kubectl and gcloud CLI nor are they allowed to be installed. So I am trying to do everything through REST API.
For creating the cluster through REST, I can use GCE Rest API with bearer token retrieved from Google OAuth Playground. Something like:
curl -i -X GET -H "Accept: application/json" -H "Content-Type: application/json" -H "Content-Length: 0" -H "Authorization: Bearer $MyBearerToken https://container.googleapis.com/v1/projects/$PROJECT_ID/zones/$ZONE/serverconfig
I can also find Kubernetes REST API reference here. So my question is: How do I retrieve, say pod information, from my GCE Kubernetes cluster, using REST api and REST api only?
I tried with kubectl get pods --v=8, and it's using GET https://${Kubenetes_IP}/api/v1/namespaces/default/pods. But when I use the same api endpoint to curl with my GCE bearer. It gives me Unzuthorized error message.
# curl --insecure -H "Authorization: Bearer $MyBearerToken" https://${Kubenetes_IP}/api/v1/namespaces/default/pods
Unauthorized
I am guessing because I need to use a different bearer token, or some other authentication method. I am wondering if anyone got a quick programtic one-liner? (Without resorting to kubectl or gcloud)
Reference
This answer affirms that there is a way using bearer token, but didn't give a pointer or example
This answer also seems promising, but all the link provided are broken (and api are deprecated as well)
This answer assumes kubectl and gcloud are installed, which is not allowed in my current use case.
Token can be retrieve from Google OAuth Playground
Kubernetes can be reached by the following curl command via REST API
# curl --insecure -H "Authorization: Bearer $MyBearerToken" https://${Kubenetes_IP}/api/v1/namespaces/default/pods
Kubernetes Master IP can be retrieved with kubectl get pods --v=8 and it could probably be retrieved somewhere from GCE Web GUI as well.
Full Kubernetes REST API can be found here
Make sure the token has not yet expired, and I think right now the default TTL is 1 hour.
When you authorize the OAuth2 playground to give you a token, it exchanges an Authorization Code for a Refresh Token and an Access Token.
The Access Token (from the OAuth2 playground) is valid for 1 hour.
The Refresh Token is a long-lived credential that is used to obtain new Access Tokens from the Authorization Server.
If you try to authenticate to the "Resource Owner" (in this case, Kubernetes) with an expired access token, it will respond with an HTTP 401 error.