在API请求中添加“SignedHeaders”参数的值。下面是一个AWS4签名的示例:
import hmac, hashlib, base64
def sign(key, msg):
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
def get_signature_key(key, date_stamp, region_name, service_name):
k_date = sign(('AWS4' + key).encode('utf-8'), date_stamp)
k_region = sign(k_date, region_name)
k_service = sign(k_region, service_name)
k_signing = sign(k_service, 'aws4_request')
return k_signing
def get_auth_header(access_key, secret_key, method, endpoint, path, query_params, headers, payload, region):
timestamp = '20210615T104237Z'
datestamp = '20210615'
HTTPRequestMethod = method.upper()
CanonicalURI = path
CanonicalQueryString = '&'.join(sorted(query_params))
CanonicalHeaders = 'host:' + endpoint + '\n' + 'x-amz-date:' + timestamp + '\n'
SignedHeaders = 'host;x-amz-date'
payload_hash = hashlib.sha256(payload.encode('utf-8')).hexdigest()
CanonicalRequest = HTTPRequestMethod + '\n' + CanonicalURI + '\n' + CanonicalQueryString + '\n' + CanonicalHeaders + '\n' + SignedHeaders + '\n' + payload_hash
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/s3/aws4_request'
string_to_sign = algorithm + '\n' + timestamp + '\n' + credential_scope + '\n' + hashlib.sha256(CanonicalRequest.encode('utf-8')).hexdigest()
signing_key = get_signature_key(secret_key, datestamp, region, 's3')
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
Authorization = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + SignedHeaders + ', ' + 'Signature=' + signature
headers.update({'x-amz-date': timestamp, 'Authorization': Authorization})
return headers