【问题标题】:Getting 403 SignatureDoesNotMatch when uploading to Google Cloud Storage?上传到 Google Cloud Storage 时收到 403 SignatureDoesNotMatch?
【发布时间】:2018-05-03 01:28:30
【问题描述】:

我正在尝试将客户端上的音频文件直接上传到我的 Google Cloud Storage 存储桶,以避免服务器端上传(有文件大小限制)。

我的问题:我在上传时收到 403 SignatureDoesNotMatch 错误。

这是响应中的错误:

<Error>
<Code>SignatureDoesNotMatch</Code>
<Message> The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method</Message>
<StringToSign>
PUT

audio/mp3
1511112552
/bucketname/pathtofile/019%20-%20top%20cntndr%20V1.mp3
</StringToSign>
</Error>

我创建了一个签名的网址。它看起来像这样:

https://storage.googleapis.com/google-testbucket/testdata.txt?GoogleAccessId=
1234567890123@developer.gserviceaccount.com&Expires=1331155464&Signature=BCl
z9e4UA2MRRDX62TPd8sNpUCxVsqUDG3YGPWvPcwN%2BmWBPqwgUYcOSszCPlgWREeF7oPGowkeKk
7J4WApzkzxERdOQmAdrvshKSzUHg8Jqp1lw9tbiJfE2ExdOOIoJVmGLoDeAGnfzCd4fTsWcLbal9
sFpqXsQI8IQi1493mw%3D

签名的 url 是按照在此处的 Google 文档中找到的指导方针构建的 https://cloud.google.com/storage/docs/access-control/create-signed-urls-program

但是,处理此签名 URL 的客户端 javascript 部分在文档中非常不清楚。

这是我的 python 代码,用于创建和返回签名的 url。

GOOGLE_SERVICE_CREDENTIALS = 'google-service-credentials.json'

def get_signed_url(request):
    filename = request.GET.get('filename')
    expiration = request.GET.get('expiration')
    type = request.GET.get('type')
    signed_url = CloudStorageSignedURL(
                method='PUT',
                file_name=filename,
                expiration_m=expiration,
                content_type=type
                )
    signed_url = signed_url.sign_url()


    return JsonResponse({ 'signed_url': signed_url })






class CloudStorageSignedURL(object):


    def __init__(self, method, file_name, expiration_m, content_type):
        self.HTTP_method = method
        self.content_type = 'content-type: ' + content_type
        self.expiration = int(expiration_m)
        self.file_name = file_name


    def sign_url(self):


        expiration_dt = datetime.utcnow() + timedelta(minutes=self.expiration)
        expiration = int(time.mktime( expiration_dt.timetuple() ))
        bucket_path = '/' + settings.CLOUD_STORAGE_BUCKET + '/dev/tests/' + self.file_name
        signature_string = self.HTTP_method + '\n' + '\n' + self.content_type + "\n" + str(expiration) + '\n' + bucket_path
        print(signature_string)
        creds = ServiceAccountCredentials.from_json_keyfile_name(GOOGLE_SERVICE_CREDENTIALS)
        client_email = creds.service_account_email
        signature = creds.sign_blob(signature_string)[1]
        encoded_signature = base64.urlsafe_b64encode(signature).decode('utf-8')
        base_url = settings.CLOUD_STORAGE_ROOT + 'dev/tests/' + self.file_name


        return base_url + '?GoogleAccessId=' + client_email + '&Expires=' + str(expiration) + '&Signature=' + encoded_signature

上传文件的客户端 Javascript

import $ from 'jquery';
import axios from 'axios';



$("document").ready( () => {
  console.log('window loaded');


  $("#id_audio_file").change(function() {

    const file = this.files[0]

    const url = window.location.href.replace('submit/', 'upload/');
    $.get(url + `?filename=${file.name}&expiration=10&type=${file.type}`, (data) => {
      upload(data.signed_url, file);
    })

  });
});



function upload(url, file) {

  const config = {
    headers: {
      'Content-Type': file.type,
    }
  }

  axios.put(url, file, config)
    .then(function (res) {
      console.log(res);
    })
    .catch(function (err) {
      console.log(err);
    });
}

我真的觉得我在这里涵盖了所有基础,但我显然错过了一些细节。任何帮助将不胜感激!

【问题讨论】:

  • Expires=1331155464 表示该 URL 提供的访问权限大约在 5 年前过期。不过,错误应该是:&lt;Error&gt; &lt;Code&gt;ExpiredToken&lt;/Code&gt; &lt;Message&gt;The provided token has expired.&lt;/Message&gt; &lt;Details&gt;Request has expired: timestamp&lt;/Details&gt; &lt;/Error&gt; 。我建议使用the API explorer 生成签名作为sign_url 的替代品,用于测试

标签: javascript python file-upload google-cloud-platform google-cloud-storage


【解决方案1】:

首先,确保您使用的服务帐号具有将文件上传到存储桶的适当权限:通过IAM settingsaccess control

如果设置了,那就是代码问题。我已经尝试过您的方法,而不是手动创建签名的 url,但它对我来说也失败了,同样的错误。但是,我已经设法使用来自the Google Cloud python client librarygenerate_signed_url 方法通过签名URL 上传文件。少说话,多代码:

from google.oauth2 import service_account
import base64
import json
from datetime import datetime, timedelta
import time
import requests
from google.cloud import storage

# client = storage.Client()
# bucket = client.get_bucket('a-test-bucket')
# blob = bucket.blob('/test/mpthreetest.mp3')

GOOGLE_SERVICE_CREDENTIALS = 'signed_url_account.json'
FILENAME = 'mpthreetest.mp3'
EXPIRATION = 1511826970  # epoch time
TYPE = 'audio/mp3'

creds = service_account.Credentials.from_service_account_file(GOOGLE_SERVICE_CREDENTIALS)
bucket = storage.Client().get_bucket('a-test-bucket')
blob = bucket.blob('test/mpthreetest.mp3')

signed_url = blob.generate_signed_url(method='PUT', expiration=EXPIRATION, content_type=TYPE, credentials=creds)

print (signed_url)

req = requests.put(signed_url, open(FILENAME), headers={'Content-Type': TYPE})
print(req.content)

【讨论】:

  • 这种方法是否适用于将文件放入存储桶中?我正在尝试为存储桶(PUT)生成一个签名的 url 并将其发送到浏览器,以便浏览器可以直接上传到存储桶而无需通过服务器。拉我的头发试图让它发挥作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-11
  • 2018-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-06-11
  • 1970-01-01
相关资源
最近更新 更多