gpt4 book ai didi

aws-lambda - 如何将 Cognito 用户池授权者添加到 Cloud Formation Template 中的 Lambda 代理集成?

转载 作者:行者123 更新时间:2023-12-03 07:28:15 24 4
gpt4 key购买 nike

我有以下云形成 JSON 模板。此模板是 AWS 为 C#(Dotnet) Web API Lambda 代理集成提供的默认模板。

{
"AWSTemplateFormatVersion" : "2010-09-09",
"Transform" : "AWS::Serverless-2016-10-31",
"Description" : "An AWS Serverless Application that uses the ASP.NET Core framework running in Amazon Lambda.",

"Parameters" : {
"ShouldCreateBucket" : {
"Type" : "String",
"AllowedValues" : ["true", "false"],
"Description" : "If true then the S3 bucket that will be proxied will be created with the CloudFormation stack."
},
"BucketName" : {
"Type" : "String",
"Description" : "Name of S3 bucket that will be proxied. If left blank a new table will be created.",
"MinLength" : "0"
}
},

"Conditions" : {
"CreateS3Bucket" : {"Fn::Equals" : [{"Ref" : "ShouldCreateBucket"}, "true"]},
"BucketNameGenerated" : {"Fn::Equals" : [{"Ref" : "BucketName"}, ""]}
},

"Resources" : {

"ProxyFunction" : {
"Type" : "AWS::Serverless::Function",
"Properties": {
"Handler": "DotnetLanmada::DotnetLanmada.LambdaEntryPoint::FunctionHandlerAsync",
"Runtime": "dotnetcore2.0",
"CodeUri": "",
"MemorySize": 256,
"Timeout": 30,
"Role": null,
"Policies": [ "AWSLambdaFullAccess" ],
"Environment" : {
"Variables" : {
"AppS3Bucket" : { "Fn::If" : ["CreateS3Bucket", {"Ref":"Bucket"}, { "Ref" : "BucketName" } ] }
}
},
"Events": {
"PutResource": {
"Type": "Api",
"Properties": {
"Path": "/{proxy+}",
"Method": "ANY"
}
}
}
}
},

"Bucket" : {
"Type" : "AWS::S3::Bucket",
"Condition" : "CreateS3Bucket",
"Properties" : {
"BucketName" : { "Fn::If" : ["BucketNameGenerated", {"Ref" : "AWS::NoValue" }, { "Ref" : "BucketName" } ] }
}
}
},

"Outputs" : {
"S3ProxyBucket" : {
"Value" : { "Fn::If" : ["CreateS3Bucket", {"Ref":"Bucket"}, { "Ref" : "BucketName" } ] }
}
}
}

此模板创建 Lambda 函数、API 网关和 S3 存储桶。所有对 API 网关的请求都被代理到 Lambda 函数。我想使用现有的 Cognito 用户池对 API 网关的所有请求进行身份验证。基本上,API 网关将有一个 Cognito 用户池授权者,并且代理功能将通过该授权者获得授权。由于 API 网关创建部分隐藏在此模板中,我不知道如何在此处添加 Cognito 用户池授权者。

提前致谢。

最佳答案

实现您想要的目标的一种方法是导出 Lambda 函数的 ARN,然后将其导入您的 API 网关堆栈。

要导出函数的 ARN,请在 Outputs 部分中添加:

"Function": {
"Value": ProxyFunction.Arn,
"Export": {
"Name": "ProxyFunction::Arn"
}
}

您还需要拥有 API Gateway 的调用权限才能调用您的函数。您可以将这样的内容添加到堆栈中:

"LambdaInvocationPermission": {
"Type": "AWS::Lambda::Permission",
"Properties": {
"Action": "lambda:InvokeFunction",
"FunctionName": { "Fn::GetAtt" : [ "ProxyFunction", "Arn" ] },
"Principal": "apigateway.amazonaws.com"
}
}

然后在 API 网关堆栈中,您可以使用

引用函数的 ARN
{ "Fn::ImportValue" : "ProxyFunction::Arn" }

关于aws-lambda - 如何将 Cognito 用户池授权者添加到 Cloud Formation Template 中的 Lambda 代理集成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48599445/

24 4 0