在不使用显式密钥文件的情况下从Google Cloud Function生成Cloud Storage签名的URL [英] Generating Cloud Storage Signed URL from Google Cloud Function without using explicit key file

查看:74
本文介绍了在不使用显式密钥文件的情况下从Google Cloud Function生成Cloud Storage签名的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个预签名的上传URL到存储桶,并希望避免显式引用json密钥.

I'd like to create a pre-signed upload URL to a storage bucket, and would like to avoid an explicit reference to a json key.

当前,我正在尝试使用默认的App Engine服务帐户进行操作

Currently, I'm attempting to do this with the Default App Engine Service Account

我正尝试与此答案一起使用,但出现此错误:

I'm attempting to follow along with this answer but am getting this error:

AttributeError:您需要一个私钥来对凭据进行签名.您当前使用的< class凭据'google.auth.compute_engine.credentials.Credentials'>只是包含一个令牌.看 https://googleapis.dev/python/google-api-core/latest/auth.html#setting-up-a-service-account 有关更多详细信息.

我的Cloud Function代码如下:

My Cloud Function code looks like this:

from google.cloud import storage
import datetime
import google.auth

def generate_upload_url(blob_name, additional_metadata: dict = {}):
    credentials, project_id = google.auth.default()
    # Perform a refresh request to get the access token of the current credentials (Else, it's None)
    from google.auth.transport import requests

    r = requests.Request()
    credentials.refresh(r)

    client = storage.Client()
    bucket = client.get_bucket("my_bucket")
    blob = bucket.blob(blob_name)
    
    service_account_email = credentials.service_account_email
    print(f"attempting to create signed url for {service_account_email}")
    url = blob.generate_signed_url(
        version="v4",
        service_account_email=service_account_email,
        access_token=credentials.token,
        # This URL is valid for 120 minutes
        expiration=datetime.timedelta(minutes=120),
        # Allow PUT requests using this URL.
        method="PUT",
        content_type="application/octet-stream",
        
    )
    return url


def get_upload_url(request):
    blob_name = get_param(request, "blob_name")
    url = generate_upload_url(blob_name)
    return url

推荐答案

使用签名网址的v4版本时,

When you use version v4 of signed URL, the first line of the method calls ensure_signed_credentialsmethod that check if the current service account can generate a signature in standalone mode (so with a private key). And so, that's break the current behavior.

在函数的注释中,清楚地描述了需要服务帐户JSON文件

In the comment of the function, it's clearly describe that a service account JSON file is required

        If you are on Google Compute Engine, you can't generate a signed URL.
        Follow `Issue 922`_ for updates on this. If you'd like to be able to
        generate a signed URL from GCE, you can use a standard service account
        from a JSON file rather than a GCE service account.

因此,请改用v2版本.

So, use v2 version instead.

这篇关于在不使用显式密钥文件的情况下从Google Cloud Function生成Cloud Storage签名的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆