在AWS SAM(Serverless Application Model)中,可以使用HttpApiGateway和Lambda Authorizer来授权调用Lambda函数。下面是一个包含代码示例的解决方法:
Resources:
MyHttpApi:
Type: AWS::Serverless::HttpApi
Properties:
StageName: prod
Auth:
DefaultAuthorizer: MyAuthorizer
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: my-function/
Handler: app.lambda_handler
Runtime: python3.8
Events:
MyApi:
Type: HttpApi
Properties:
ApiId: !Ref MyHttpApi
Path: /myapi
Method: GET
MyAuthorizer:
Type: AWS::Serverless::HttpApiAuthorizer
Properties:
ApiId: !Ref MyHttpApi
IdentitySource: $request.header.Authorization
AuthorizerUri: arn:aws:apigateway::lambda:path/2015-03-31/functions/arn:aws:lambda:::function:MyAuthorizer/invocations
AuthorizerResultTtlInSeconds: 300
在上面的示例中,创建了一个HttpApi(MyHttpApi),以及一个Lambda函数(MyFunction)。HttpApi使用了一个自定义的Lambda授权器(MyAuthorizer)。注意修改其中的CodeUri
、Handler
、Runtime
等属性,以适配你的实际情况。
import json
def lambda_handler(event, context):
# 获取请求中的Authorization头
auth_header = event['headers'].get('Authorization')
# 验证token或其他授权逻辑
# ...
# 返回授权结果
if is_authorized:
return generate_policy('user', 'Allow', event['methodArn'])
else:
return generate_policy('user', 'Deny', event['methodArn'])
def generate_policy(principal_id, effect, resource):
policy_document = {
'principalId': principal_id,
'policyDocument': {
'Version': '2012-10-17',
'Statement': [
{
'Action': 'execute-api:Invoke',
'Effect': effect,
'Resource': resource
}
]
}
}
return policy_document
在上面的示例中,lambda_handler
函数根据请求中的Authorization头进行授权,可以自行实现自己的授权逻辑。根据授权结果,使用generate_policy
函数生成一个包含授权信息的策略文档。
使用AWS SAM CLI工具,运行以下命令来部署SAM应用:
sam deploy --guided
按照提示进行配置,并部署SAM应用。
使用任意HTTP客户端,发送GET请求到HttpApi的URL(例如:https://
这是一个基本的使用AWS SAM HttpApiGateway和Lambda Authorizer授权调用Lambda函数的解决方法。根据实际需求,可以进一步扩展和定制授权逻辑。