我有一个工作正常的 API 授权器,但我想在我的 lambda 函数(用 python 编写)中访问获得的 principalId。我在其他答案中看到他们建议使用模板映射,但我根本无法让它发挥作用。我使用以下内容创建了一个简单的映射:
{
"userId" : "$context.authorizer.principalId"
}
对于 Content-Type: application/json 并尝试使用这两个选项:
- 当没有模板与请求 Content-Type 标头匹配时
- 当没有定义模板时(推荐)
但无论如何,当我尝试访问函数上的变量时,它会给我一个 keyError。我还尝试了默认为您提供的映射并通过“上下文”访问它,但我也得到了一个 keyError。
要访问它,我只需使用:
event["userId"]
或者
event["context"]
但在这两种情况下,我都会得到 keyError。
更新1: 这是仅供参考的代码,函数和授权者在API中都可以正常工作,唯一的问题是当我尝试在函数中获取principalId时。
拉姆达函数代码:
def handler(event, context):
print(event['userId'])
# Your code goes here!
documento = event.get("documento")
tipo = event.get("tipo")
documento_bytes = base64.decodebytes(documento.encode('utf-8'))
if tipo == "ine":
return get_info_ine(documento_bytes)
else:
respuesta = {
"estatus" : "ERROR",
"mensaje" : "El tipo de documento <%s> enviado no existe" % tipo,
"claveMensaje" : 2
}
return respuesta
授权人代码:
import psycopg2
import base64
import re
from perfil import *
def handler(event, context):
login_string = event["headers"]["Authorization"]
login_string = re.sub('^Basic ', '', login_string)
username, password = base64.b64decode(
login_string).decode("UTF-8").split(':')
connection, cursor = get_connection(hostname, dbuser, dbpass, database)
cursor.execute("a query here")
id = 0
effect = "Deny"
for record in cursor:
id = record[0]
effect = "Allow"
return {
"principalId": str(id),
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": effect,
"Resource": "arn:aws:execute-api:us-west-2:12345678910:xyz/*/POST/*"
}
]
}
}