AWS SigV4请求签名不匹配 [英] AWS SigV4 request signature does not match

查看:643
本文介绍了AWS SigV4请求签名不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用Rest API创建事物类型时,我收到带有以下错误消息的Invalid Request消息.我没有使用aws-sdk而是python rest client.

I am getting Invalid Request with below error message when trying to create a thing-type using Rest API. I am not using aws-sdk rather python rest client.

我遵循了此处给出的步骤使用sigv4签署请求.此处给出的示例适用于列出Thing-Type.因此,我使用的凭据是正确的.错误消息:

I followed the steps given here to sign the request using sigv4. The example given there is working for listing the Thing-Types. So the credentials I am using, are correct. Error Message :

响应码:403

{"message":"我们计算出的请求签名与您提供的签名不匹配.请检查您的AWS Secret Access密钥并签名 方法.有关详细信息,请查阅服务文档.}

{"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."}

我正在使用的代码:

# See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
# This version makes a POST request and passes request parameters
# in the body (payload) of the request. Auth information is passed in
# an Authorization header.
import sys, os, base64, datetime, hashlib, hmac
import requests  # pip install requests

# ************* REQUEST VALUES *************
method = 'POST'
service = 'execute-api'
api = 'https://iot.eu-west-2.amazonaws.com/thing-types/GasSensor'
request_parameter='{"thingTypeProperties":{"searchableAttributes":  ["gas"],"thingTypeDescription":"Devices that reports gas level readings"}}'
host = api.split('/')[2] if api.count('/') >= 2 else ''
region = api.split('.')[1] if api.count('.') >= 1 else ''
endpoint = api.split('?')[0] if api.count('?') >= 0 else api
#request_parameters = api.split('?')[1] if api.__contains__('?') else ''


# Request parameters for CreateTable--passed in a JSON block.
request_parameters = payload
print(host + ' $ ' + region + ' $ ' + endpoint + ' $ ' + request_parameters)
# Key derivation functions. See:
# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
def sign(key, msg):
    return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()

def getSignatureKey(key, date_stamp, regionName, serviceName):
    kDate = sign(('AWS4' + key).encode('utf-8'), date_stamp)
    kRegion = sign(kDate, regionName)
    kService = sign(kRegion, serviceName)
    kSigning = sign(kService, 'aws4_request')
    return kSigning

# Read AWS access key from env. variables or configuration file. Best practice is NOT
# to embed credentials in code.
access_key = 'XXXXXXXXXXXXX'
secret_key = 'XXXXXXXXXXXXXX'   
if access_key is None or secret_key is None:
    print
    'No access key is available.'
    sys.exit()

# Create a date for headers and the credential string
t = datetime.datetime.utcnow()
amz_date = t.strftime('%Y%m%dT%H%M%SZ')
date_stamp = t.strftime('%Y%m%d')  # Date w/o time, used in credential scope

# ************* TASK 1: CREATE A CANONICAL REQUEST *************
# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html

# Step 1 is to define the verb (GET, POST, etc.)--already done.

# Step 2: Create canonical URI--the part of the URI from domain to query
# string (use '/' if no path)
canonical_uri = '/'

## Step 3: Create the canonical query string. In this example, request
# parameters are passed in the body of the request and the query string
# is blank.
canonical_querystring = ''

# Step 4: Create the canonical headers. Header names must be trimmed
# and lowercase, and sorted in code point order from low to high.
# Note that there is a trailing \n.
canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'

# Step 5: Create the list of signed headers. This lists the headers
# in the canonical_headers list, delimited with ";" and in alpha order.
# Note: The request can include any headers; canonical_headers and
# signed_headers include those that you want to be included in the
# hash of the request. "Host" and "x-amz-date" are always required.
# For DynamoDB, content-type and x-amz-target are also required.
signed_headers = 'content-type;host;x-amz-date'

# Step 6: Create payload hash. In this example, the payload (body of
# the request) contains the request parameters.
payload_hash = hashlib.sha256(request_parameters.encode('utf-8')).hexdigest()

# Step 7: Combine elements to create create canonical request
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash

# ************* TASK 2: CREATE THE STRING TO SIGN*************
# Match the algorithm to the hashing algorithm you use, either SHA-1 or
# SHA-256 (recommended)
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = date_stamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' + amz_date + '\n' + credential_scope + '\n' + hashlib.sha256(
    canonical_request.encode('utf-8')).hexdigest()

# ************* TASK 3: CALCULATE THE SIGNATURE *************
# Create the signing key using the function defined above.
signing_key = getSignatureKey(secret_key, date_stamp, region, service)

# Sign the string_to_sign using the signing_key
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()

# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************
# Put the signature information in a header named Authorization.
authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature

# # Python note: The 'host' header is added automatically by the Python 'requests' library.
headers = {'Content-Type': content_type,
           'X-Amz-Date': amz_date,
           'Authorization': authorization_header}

# ************* SEND THE REQUEST *************
print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')

print( 'Request URL = ' + endpoint)


r = requests.post(endpoint, data=request_parameters, headers=headers)

print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
print('Response code: %d\n' % r.status_code)
print(r.text)

推荐答案

在大多数情况下,我建议为此使用图书馆.由于您使用的是requests库,因此 aws-requests-auth 是有吸引力的选择.

For most use cases, I'd recommend leaning on a library for this. Since you're using the requests library, aws-requests-auth is an attractive choice.

如果您真的有兴趣自己实施签名过程,请

If you really are interested in implementing the signing process yourself, this test suite may help you figure out what's going wrong.

我唯一看到的是您的代码:

The only thing I noticed looking at your code:

当我使用aws-requests-auth时,我的呼叫看起来像这样:

When I use aws-requests-auth, my call looks like this:

response = requests.post('https://<api-endpoint>',
                        auth=auth,
                        data= json.dumps({'payload': 'data'}))

只想调用json.dumps(),它可以对我的params对象进行字符串化处理.亚马逊的示例还为request_parameters使用了字符串.

Just wanted to call out the json.dumps(), which stringifies my params object. Amazon's sample also uses a string for the request_parameters.

我不确定payload在代码中的来源,但是请确保将其转换为字符串(如果还不是一个字符串的话).

I'm not sure where payload comes from in your code, but make sure you're turning it into a string if it isn't already one.

更新

我仔细查看了您的代码,您需要在Task 1-创建规范URI 下实现Step 2.这个URI确实是用于dynamo调用的"/",但是您的URI应该看起来像这样:

I looked at your code more closely, and you need to implement Step 2 under Task 1 - Create canonical URI. This URI is indeed "/" for the dynamo call, but yours should look something like this:

# Step 2: Create canonical URI--the part of the URI from domain to query
# string (use '/' if no path)
canonical_uri = '/thing-types/GasSensor'

此外,无论是否带有Content-Type标头,此请求都会成功.因此:

Also, this request will succeed with or without a Content-Type header. So this:

content_type='application/json'

canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'

signed_headers = 'content-type;host;x-amz-date'

这:

canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'

signed_headers = 'host;x-amz-date'

为我工作.

这篇关于AWS SigV4请求签名不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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