通常在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的新手,我正在尝试做同样的事情。
稍后,我的目标是创建一个应用程序引擎应用程序,该应用程序将公开在私有存储桶中找到的图像,因此必须具有凭据。
怎么做的?
对于身份验证,你可以依赖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-storage
Python中的软件包也是如此。在Github上查看这两个软件包的源代码可能会有所帮助。对我而言,这确实有助于了解身份验证机制。
当我在与谷歌云存储交互的笔记本电脑上开发代码时,我首先告诉gcloud SDK我的凭据是什么以及我在哪个GCP项目上工作。为此,我使用以下命令:
gcloud config set project [PROJECT_ID]
gcloud auth application-default login
你还可以将其设置DEFAULT_APPLICATION_CREDENTIALS
为指向凭证文件的环境变量。然后,在你的代码中,可以在初始化客户端时传递项目名称。例如,如果你要在其他服务器上的GCP之外运行代码,这可能会有所帮助。