AWS API Gateway 自定义授权 Lambda 的 C# 实现

use*_*570 6 c# amazon-web-services aws-sdk aws-lambda

我有一个关于使用 C# 编码的 lambda 对 AWS API Gateway 进行自定义授权的问题。在 AWS Lambdas 的文档中,函数签名如下:

returnType handler-name(inputType input, ILambdaContext context) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

需要为函数处理程序指定 inputType 和 returnType。API Gateway 中的自定义授权,inputType 和 returnTypes 应该是什么?提前致谢。

Aar*_*don 7

您可以选择强类型方法,而无需发明需要遵循所需架构的自定义类。

使用 Nuget 包:

Amazon.Lambda.APIGatewayEvents

输入架构:

https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-input.html

输出架构:

https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html

您的函数原型可以类似于:

using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;

public class Function
{
    public APIGatewayCustomAuthorizerResponse FunctionHandler(APIGatewayCustomAuthorizerRequest input, ILambdaContext context)
    {
        bool ok = false;
        // authorization logic here...
        if(input.AuthorizationToken == "up-down-left-right-a-b-select-start")
        {
            ok = true;
        }
        return new APIGatewayCustomAuthorizerResponse
        {
            PrincipalID = "***",//principal info here...
            UsageIdentifierKey = "***",//usage identifier here (optional)
            PolicyDocument = new APIGatewayCustomAuthorizerPolicy
            {
                Version = "2012-10-17",
                Statement = new List<APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>() {
                      new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement
                      {
                           Action = new HashSet<string>(){"execute-api:Invoke"},
                           Effect = ok ? "Allow" : "Deny",
                           Resource = new HashSet<string>(){  "***" } // resource arn here
                      }
                },
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)


use*_*570 1

我想发布我使用过的对我有用的解决方案。感谢 Josh Maag 为我指明了正确的方向。基本上,我创建了一些简单的类:

public class TokenAuthorizerContext
{
    public string Type { get; set; }
    public string AuthorizationToken { get; set; }
    public string MethodArn { get; set; }
}

public class AuthPolicy
{
    public PolicyDocument policyDocument { get; set; }
    public string principalId { get; set; }
}

public class PolicyDocument
{
    public string Version { get; set; }
    public Statement[] Statement { get; set; }
}

public class Statement
{
    public string Action { get; set; }
    public string Effect { get; set; }
    public string Resource { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

````

创建上述类后,我的处理程序的签名是:

public async Task<AuthPolicy> FunctionHandler(TokenAuthorizerContext request, ILambdaContext context)
Run Code Online (Sandbox Code Playgroud)

  • 查看 nuget 包“Amazon.Lambda.APIGatewayEvents”,我还在下面发布了一个示例。 (2认同)