微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从API授权程序访问lambda函数python中的principalId

如何解决从API授权程序访问lambda函数python中的principalId

我有一个可以正常工作的API授权器,但是我想在我的lambda函数(用python编写)中访问获得的principalId。 我在其他答案中看到他们建议使用模板映射,但我根本无法使它正常工作。 我使用以下内容创建了一个简单的映射:

{
    "userId" : "$context.authorizer.principalId"
}

对于Content-Type:application / json 并尝试使用以下两个选项:

  • 当没有模板与请求的Content-Type标头匹配时
  • 未定义模板时(推荐)

但是无论如何,当我尝试访问函数中的变量时,都会给我一个keyError。 我还尝试了认情况下提供给您的映射,并通过“上下文”访问它,但是我也遇到了keyError。

要访问它,我只需使用:

event["userId"]

event["context"]

但是在两种情况下我都得到keyError。

更新1: 这是仅供参考的代码,该函数和授权者在API中都可以正常工作,唯一的问题是当我尝试在函数获取PrincipalId时。

lambda函数代码

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/*"
                }
            ]
        }
    }

解决方法

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

目标是在函数中访问此ID。

授权者附加的策略可以在具有关键字属性event的输入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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。