1

我有一个工作正常的 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/*"
                }
            ]
        }
    }
4

1 回答 1

0

据我了解,授权者将来自数据库的用户 ID 放在生成的策略的 PrincipalId 中。

目标是在函数中访问这个 id。

授权方附加的策略可以在event具有 key 属性的输入对象上找到requestContext。完整路径是:event['requestContext']['authorizer']['principalId']

这是一个简单的 hello 函数,它从其授权方读取(并输出)PrincipalId 值:

def hello(event, context):
    print('event', event)
    userId = None
    if 'requestContext' in event and 'authorizer' in event['requestContext']:
        userId = event['requestContext']['authorizer']['principalId']
    body = {
        "userId": userId,
        "event": event
    }

    response = {
        "statusCode": 200,
        "headers": {
            # Required for CORS support to work
            'Access-Control-Allow-Origin': '*',
            # Required for cookies, authorization headers with HTTPS
            'Access-Control-Allow-Credentials': True,
        },
        "body": json.dumps(body)
    }

    return response

于 2020-10-21T13:22:24.690 回答