GCS Generate_Signed_Url expires upon loading

不问归期 提交于 2021-02-05 11:24:06

问题


I am implementing some code to generate a signed url for some images that are specified in a json file, this is the method used to generate them

def geturl(image_name):
    storage_client = storage.Client()
    bucket = 'Bucket Name'
    source_bucket = storage_client.get_bucket(bucket)
    blobs = source_bucket.list_blobs()
    for blob in blobs:
        if image_name == blob.name:
            url_lifetime = 3600
            serving_url = blob.generate_signed_url(url_lifetime)
            return serving_url
    return 

after this they are used in an img scr <>, however when loading the page the images do not load and following the url i receive the error

The provided token has expired Request signature expired at: 1970-01-01T10:00:00+00:00

even when changing the lifetime the error message persists


回答1:


Your parameter url_lifetime is not initialized correctly. The correct meaning is expiration date which is a value in seconds from January 1, 1970 GMT. Your expiration was one hour into 1970.

The correct method is current time + 3600 seconds.

There are many ways to get the current time. Example: int(time.time()) which returns the current time in your timezone in seconds. Typically you will want to convert the current time to GMT and then grab the seconds.

Note: In this answer, I am using GMT in the same usage as UTC.

from datetime import timezone, datetime
int(datetime.now(tz=timezone.utc).timestamp()



回答2:


Let me add two examples:

1

def _sign_gcp_blob_url(verb, obj_path, content_type, expiration):

from oauth2client.service_account import ServiceAccountCredentials

import base64

from six.moves.urllib.parse import urlencode, quote

GCS_API_ENDPOINT = 'https://storage.googleapis.com'

expiration_in_epoch = int(expiration.timestamp())

signature_string = ('{verb}\n'

                '{content_md5}\n'

                '{content_type}\n'

                '{expiration}\n'

                '{resource}')

signature = signature_string.format(verb=verb,

    content_md5='',

    content_type='',

    expiration=expiration_in_epoch,

    resource=obj_path)

creds = 

ServiceAccountCredentials.from_json_keyfile_name(settings.GOOGLE_APPLICATION_CRE DENTIALS)

signature = creds.sign_blob(signature)[1]

encoded_signature = base64.b64encode(signature)

base_url= GCS_API_ENDPOINT + obj_path

storage_account_id = creds.service_account_email

return '{base_url}?GoogleAccessId={account_id}&Expires={expiration}&Signature={signature}'.format(base_url=base_url,
    account_id=storage_account_id,
    expiration = expiration_in_epoch,
    signature=quote(encoded_signature))

Example 2

https://github.com/GoogleCloudPlatform/storage-signedurls-python/commit/828486a99e34d38fc3ccbb434899284c8b069044



来源:https://stackoverflow.com/questions/56790834/gcs-generate-signed-url-expires-upon-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!