Warm tip: This article is reproduced from serverfault.com, please click

How to authenticate with tokens in Nodejs to a private bucket in Cloud Storage

发布于 2020-12-01 08:20:57

Usually in Python what I do, I get the application default credentials, I get the access token then I refresh it to be able to authenticate to a private environment.

Code in Python:

# getting the credentials and project details for gcp project
credentials, your_project_id = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])

#getting request object
auth_req = google.auth.transport.requests.Request();

print(f"Checking Authentication : {credentials.valid}") 

print('Refreshing token ....')
credentials.refresh(auth_req)

#check for valid credentials
print(f"Checking Authentication : {credentials.valid}")     
access_token = credentials.token

credentials = google.oauth2.credentials.Credentials(access_token);

storage_client = storage.Client(project='itg-ri-consumerloop-gbl-ww-dv',credentials=credentials)

I am entirely new to NodeJS, and I am trying to make the same thing.

My goal later is to create an app engine application that would expose an image that is found in a private bucket, so credentials are a must.

How it is done?

Questioner
Khaled arja
Viewed
11
Nebulastic 2020-12-01 19:03:44

For authentication, you could rely on the default application credentials that are present within the GCP platform (GAE, Cloud Functions, VM, etc.). Then you could just run the following piece of code from the documentation:

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');
const file = bucket.file('my-existing-file.png');

In most circumstances, there is no need to explicitly use authentication packages since they are already executed underneath the google-cloud/storage package in Nodejs. The same holds for the google-cloud-storage package in Python. It could help to look at the source code of both packages on Github. For me, this really helped to understand the authentication mechanism.

When I develop code on my own laptop, that interacts with google cloud storage, I first tell the gcloud SDK what my credentials are and on which GCP project I am working. I use the following commands for this:

gcloud config set project [PROJECT_ID]
gcloud auth application-default login

You could also set DEFAULT_APPLICATION_CREDENTIALS as an environment variable that points to a credentials file. Then within your code, you could pass the project name when initializing the client. This could be helpful if you are running your code outside of GCP on another server for example.