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

node.js-如何使用Node.js中的令牌对Cloud Storage中的私有存储桶进行身份验证

(node.js - How to authenticate with tokens in Nodejs to a private bucket in Cloud Storage)

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

通常在Python中,我会获得应用程序的默认凭据,获得访问令牌,然后刷新它以能够向私有环境进行身份验证。

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)

我是NodeJS的新手,我正在尝试做同样的事情。

稍后,我的目标是创建一个应用程序引擎应用程序,该应用程序将公开在私有存储桶中找到的图像,因此必须具有凭据。

怎么做的?

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

对于身份验证,你可以依赖GCP平台(GAE,Cloud Functions,VM等)中存在的默认应用程序凭据。然后,你可以只运行文档中的以下代码

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

在大多数情况下,无需显式使用身份验证程序包,因为它们已google-cloud/storage在Node.js中程序包下执行google-cloud-storagePython中软件包也是如此。在Github上查看这两个软件包的源代码可能会有所帮助。对我而言,这确实有助于了解身份验证机制。

当我在与谷歌云存储交互的笔记本电脑上开发代码时,我首先告诉gcloud SDK我的凭据是什么以及我在哪个GCP项目上工作。为此,我使用以下命令:

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

你还可以将其设置DEFAULT_APPLICATION_CREDENTIALS为指向凭证文件的环境变量。然后,在你的代码中,可以在初始化客户端时传递项目名称。例如,如果你要在其他服务器上的GCP之外运行代码,这可能会有所帮助。