【问题标题】:authorization for API gatewayAPI网关授权
【发布时间】:2020-09-29 18:41:13
【问题描述】:

我使用本教程并成功创建了“put”端点。

https://sanderknape.com/2017/10/creating-a-serverless-api-using-aws-api-gateway-and-dynamodb/

当我遵循这个建议时,我得到了需要授权的错误..

使用您最喜欢的 REST 客户端,尝试将项目放入 DynamoDB 使用您的 API 网关 URL。

python 是我最喜欢的客户端:

import requests
api_url = "https://0pg2858koj.execute-api.us-east-1.amazonaws.com/tds"

PARAMS = {"name":  "test", "favorite_movie":"asdsf"}
r = requests.put(url=api_url, params=PARAMS)

响应是 403

我从控制台测试成功,但无法从 python 记录。

【问题讨论】:

  • 你能从有效的控制台分享测试吗?
  • 这里是从控制台成功添加条目'Sarah - Interstellar'的屏幕截图,如教程中所述。 @DanielApt github.com/shantanuo/stack_question/blob/master/…
  • 要检查两件事:1) 您的屏幕截图显示配置的 POST 方法,而不是 PUT。 2) 你的api_url 错过舞台了吗? (在教程中他们使用prod)
  • 感谢您解决了问题。 @迈克帕特里克

标签: aws-api-gateway


【解决方案1】:

解决问题的第一步是调查 AWS 在 403 响应中返回的信息。它将提供标头x-amzn-ErrorType 和错误消息,其中包含有关具体错误的信息。您可以使用curl 以详细模式 (-v) 或使用您的 Python 代码对其进行测试。请查看relevant documentation 以获得所有可能的错误原因的详细枚举。

无论如何,查看您的代码,很可能您没有向 AWS 提供必要的身份验证或授权信息。

您必须提供的信息类型取决于您配置为访问 API Gateway 中的 REST API 的 which mechanism。

例如,如果您配置了IAM based authentication,则需要设置您的 Python 代码以生成一个Authorization 标头,该标头带有从您的用户access key ID and associated secret key 派生的AWS Signature。 AWS 文档提供了an example of use with Postman。

AWS documentation 还提供了几个示例,说明如何使用python 和requests 执行此类授权。

例如,考虑使用this example 将信息发布到 DynamoDB:

# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# This file is licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License. A copy of the
# License is located at
#
# http://aws.amazon.com/apache2.0/
#
# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

# AWS Version 4 signing example

# DynamoDB API (CreateTable)

# 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 = 'dynamodb'
host = 'dynamodb.us-west-2.amazonaws.com'
region = 'us-west-2'
endpoint = 'https://dynamodb.us-west-2.amazonaws.com/'
# POST requests use a content type header. For DynamoDB,
# the content is JSON.
content_type = 'application/x-amz-json-1.0'
# DynamoDB requires an x-amz-target header that has this format:
#     DynamoDB_<API version>.<operationName>
amz_target = 'DynamoDB_20120810.CreateTable'

# Request parameters for CreateTable--passed in a JSON block.
request_parameters =  '{'
request_parameters +=  '"KeySchema": [{"KeyType": "HASH","AttributeName": "Id"}],'
request_parameters +=  '"TableName": "TestTable","AttributeDefinitions": [{"AttributeName": "Id","AttributeType": "S"}],'
request_parameters +=  '"ProvisionedThroughput": {"WriteCapacityUnits": 5,"ReadCapacityUnits": 5}'
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 = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
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' + 'x-amz-target:' + amz_target + '\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;x-amz-target'

# 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 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

# For DynamoDB, the request can include any headers, but MUST include "host", "x-amz-date",
# "x-amz-target", "content-type", and "Authorization". Except for the authorization
# header, the headers must be included in the canonical_headers and signed_headers values, as
# noted earlier. Order here is not significant.
# # Python note: The 'host' header is added automatically by the Python 'requests' library.
headers = {'Content-Type':content_type,
           'X-Amz-Date':amz_date,
           'X-Amz-Target':amz_target,
           '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)

我认为它可以很容易地适应您的需求。

在控制台中,一切正常,因为当您在 API Gateway 中调用 REST 端点时,您将连接到已通过身份验证并有权访问这些 REST 端点的用户。

【讨论】:

  • curl 会返回消息“缺少身份验证令牌”,即使在方法请求中将 Authorization 设置为 NONE。我正在寻找 Python 解决方案(不是 Postman)。我已经按照文章中提到的完全相同的步骤来创建端点。
  • 当您将 Authorization 设置为 NONE 时,您是否重新部署了 API?在部署 API 之前,对 API 设置执行的更改不会生效。请同时验证 API Key Required 是否设置为 false:docs.aws.amazon.com/apigateway/latest/developerguide/…。请理解,我只是想帮助您:我指出 Postman 是因为这是 AWS 在其文档中包含的内容,并且因为它是检查一切是否正常的简单方法。无论如何,我很乐意修改答案以包含必要的 Python 代码。
  • 我用一个示例更新了答案,说明如何使用python and python```requests 向 AWS 发出授权的 API 请求。希望对你有帮助。
  • 感谢您的回答。它帮助我朝着正确的方向前进。
猜你喜欢
  • 1970-01-01
  • 2018-11-19
  • 2020-01-12
  • 2017-11-07
  • 1970-01-01
  • 2017-12-29
  • 2019-04-22
  • 2020-02-24
  • 1970-01-01
相关资源
最近更新 更多