简体   繁体   English

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

[英]C# implementation of AWS API Gateway Custom Authorization Lambda

I had a question with regards to custom authorization for AWS API Gateway using a lambda coded in C#. 我对使用C#编码的lambda对AWS API Gateway的自定义授权提出了疑问。 In the documentation for AWS Lambdas, the function signature is as follows: 在AWS Lambdas的文档中,函数签名如下:

returnType handler-name(inputType input, ILambdaContext context) {
   ...
}

The inputType and returnType need to be specified for the function handler. 需要为函数处理程序指定inputType和returnType。 For custom authorization in API Gateway, what should the inputType and returnTypes be? 对于API网关中的自定义授权,inputType和returnTypes应该是什么? Thanks in advance. 提前致谢。

I thought I would elaborate this a bit. 我想我会详细说明一下。 This uses part of what was done here as well as tried to make it like the example they give us here. 这使用了在这里完成的部分工作,并试图使它像他们在这里给我们的例子。 http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html

I am not sure if it needs to be async or not? 我不确定它是否需要异步? I didn't and this seemed to work pretty well for a basic start. 我没有,这对于一个基本的开始似乎工作得很好。

public class Authorize
{
    public Authorize() { }

    public AuthPolicy AuthorizeHandler(TokenAuthorizerContext request, ILambdaContext context)
    {
        var token = request.AuthorizationToken;

        switch (token.ToLower())
        {
            case "allow":
                return generatePolicy("user", "Allow", request.MethodArn);
        }

        return null;
    }

    private AuthPolicy generatePolicy(string principalId, string effect, string resource)
    {

        AuthPolicy authResponse = new AuthPolicy();
        authResponse.policyDocument = new PolicyDocument();
        authResponse.policyDocument.Version = "2012-10-17";// default version
        authResponse.policyDocument.Statement = new Statement[1];

        Statement statementOne = new Statement();
        statementOne.Action = "execute-api:Invoke"; // default action
        statementOne.Effect = effect;
        statementOne.Resource = resource;

        authResponse.policyDocument.Statement[0] = statementOne;

        return authResponse;
    }

}
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; }
}

You can opt for a strongly-typed approach without inventing custom classes that need to follow the required schema. 您可以选择强类型方法,而无需发明需要遵循所需模式的自定义类。

Use Nuget package: 使用Nuget包:

Amazon.Lambda.APIGatewayEvents Amazon.Lambda.APIGatewayEvents

Input schema: 输入架构:

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-input.html

Output schema: 输出架构:

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

Your function prototype can then resemble: 您的函数原型可以类似于:

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
                      }
                },
            }
        };
    }
}

I wanted to post the solution that I used that worked for me. 我想发布我用过的解决方案。 Thanks to Josh Maag for pointing me in the right direction. 感谢Josh Maag指出我正确的方向。 Basically, I created a few simple classes: 基本上,我创建了一些简单的类:

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; }
}

``` ```

With the above classes created, the signature to my handler is: 创建上面的类后,我的处理程序的签名是:

public async Task<AuthPolicy> FunctionHandler(TokenAuthorizerContext request, ILambdaContext context)

You should really take a look at the following link and try to follow it through. 你应该真正看看以下链接,并尝试遵循它。 The full tutorial is written using Python, so if you're unfamiliar with it, just do your best to follow along and read the full walk-through, but this link will explain the C# portion: 完整的教程是使用Python编写的,所以如果您不熟悉它,请尽量按照并阅读完整的演练,但此链接将解释C#部分:

http://docs.aws.amazon.com/lambda/latest/dg/get-started-step5-optional.html http://docs.aws.amazon.com/lambda/latest/dg/get-started-step5-optional.html

Essentially, the string: 基本上,字符串:

returnType handler-name(inputType input, ILambdaContext context) {

Would be something like this (copied from the AWS page): 会是这样的(从AWS页面复制):

public string MyHandler(int count, ILambdaContext context) { ... }

public is added as a scope modifier, the returnType the developer has chosen is string the handler-name is MyHandler and the inputType is int public被添加为范围修饰符,开发人员选择的returnTypestringhandler-nameMyHandlerinputTypeint

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM