简体   繁体   English

API网关-自定义授权者无效

[英]API Gateway - Custom Authorizer was not working

I have run into some trouble configuring/using Authentication on AWS ApiGateway. 我在AWS ApiGateway上配置/使用身份验证时遇到了一些麻烦。 I already have my lambda function set up with a code the receives the AWS authentication model, see below, which basically decodifies the JWT token and verifies if the given user can access the resource: 我已经使用代码设置了lambda函数,该代码接收AWS身份验证模型,请参见下文,该模型基本上将JWT令牌解码并验证给定用户是否可以访问资源:

{
"type": "TOKEN",
"authorizationToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjotMTU1LCJwcm9kdWN0IjoiQmlsbGlvblJ1biIsInBlcm1pc3Npb25fbGV2ZWwiOjEsInNhbHQiOiJzZWNyZXRfcGhyYXNlIn0.3gZUFITe8or2mPWBAZlOxdcGF6-ybykHVsMRsqoUI_8",
"methodArn": "arn:aws:execute-api:us-east-1:123456789012:example/prod/POST/{proxy+}"

} }

See below the sample outputs from ApiGateway documentation. 请参阅下面的ApiGateway文档中的示例输出。 The first one is when user is successfully verified (permission granted) and the second one is when user fails to verify (permission denied): 第一个是成功验证用户(授予权限)的时间,第二个是用户无法验证(拒绝权限)的时间:

{
"principalId": "users",
"policyDocument": {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "execute-api:Invoke",
            "Effect": "Allow",
            "Resource": "arn:aws:execute-api:REGION:AWS_ACCOUNT:example/prod/POST/{proxy+}"
        }
    ]
},
"context": {
    "user_id": XXX,
}

} }

Permission denied: 没有权限:

{
"principalId": "users",
"policyDocument": {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "execute-api:Invoke",
            "Effect": "Deny",
            "Resource": "arn:aws:execute-api:REGION:AWS_ACCOUNT:example/prod/POST/{proxy+}"
        }
    ]
}

} }

The problem is: Every single time I test the custom authorization function, the return status is 200 (instead of 401) and the permission is granted (even when I send wrong tokens). 问题是:每次我测试自定义授权功能时,返回状态都是200(而不是401),并且授予了许可(即使当我发送错误的令牌时)。

Also, I really feel like it is not even testing anything, although the screen shows that the custom authentication function is enabled. 另外,尽管屏幕显示启用了自定义身份验证功能,但我确实感觉它甚至没有进行任何测试。

Resource showing custom authorizer 显示自定义授权者的资源

Inside resource 内部资源

Custom Authorizer 定制授权人

Invalid Token 令牌无效

Valid Token 有效令牌

------- EDIT ------- -------编辑-------

Here the code how I implemented the output: 这是我如何实现输出的代码:

def generate_policy(principal_id, effect, resource, context=None):
doc = {
    'principalId': principal_id,
    'policyDocument': {
        'Version': '2012-10-17',
        'Statement': [{
            'Action': 'execute-api:Invoke',
            'Effect': effect,
            'Resource': resource
        }]
    }
}
if context:
    doc["context"] = context
return doc

So you can call like this to "allow": 因此,您可以像这样调用“ allow”:

generate_policy("users", "Allow", method_arn, auth_info)

Or like this to "deny": 或像这样“拒绝”:

generate_policy("users", "Deny", method_arn)

-------- EDIT AGAIN ------ Gist with my all code: --------再次编辑------要点我所有的代码:

https://gist.github.com/hermogenes-db18/1ccf3eb8273f266a3fa02643dcfd39bd https://gist.github.com/hermogenes-db18/1ccf3eb8273f266a3fa02643dcfd39bd

.Net Core (C#) version of Custom Authorizer .Net Core(C#)版本的自定义授权者

public class Function
      {
      public AuthPolicy FunctionHandler(TokenAuthorizerContext request, 
       ILambdaContext context)
        {
            var token = request.AuthorizationToken;
            var resourcePath = Environment.GetEnvironmentVariable("resourcePath");
            if (string.IsNullOrEmpty(token))
            {
                return generatePolicy("user", "Deny", request.MethodArn);
            }
            AuthPolicy policy;
                var client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Add("Authorization", token);
                var dsresponse = 
            client.GetAsync(Environment.GetEnvironmentVariable("validationURL")).Result;
                if (dsresponse.IsSuccessStatusCode)
                {
                    policy = generatePolicy("user", "Allow", resourcePath);
                }
                else
                {
                    policy = generatePolicy("user", "Deny", resourcePath);
                }
            return policy;
        }

        private AuthPolicy generatePolicy(string principalId, string effect, string 
        resourcePath)
        {
            AuthPolicy authResponse = new AuthPolicy();
            authResponse.policyDocument = new PolicyDocument();
            authResponse.policyDocument.Version = "2012-10-17";// default version
            authResponse.policyDocument.Statement = new Statement[1];

            Statement statement = new Statement();
            statement.Action = "execute-api:Invoke"; // default action
            statement.Effect = effect;
            statement.Resource = resourcePath;
            authResponse.policyDocument.Statement[0] = statement;
            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; }
    }

Response: 响应:

Request Denied: 请求被拒绝:

{
        "policyDocument": {
        "Version": "2012-10-17",
        "Statement": [
          {
            "Action": "execute-api:Invoke",
            "Effect": "Deny",
            "Resource": "arn:aws:execute-api:us-east-2:AccountId:API_Id/*"
          }
        ]
       },
       "principalId": null
     }

Request Allowed: 允许的请求:

   {
    "policyDocument": {
    "Version": "2012-10-17",
    "Statement": [
      {
        "Action": "execute-api:Invoke",
        "Effect": "Allow",
        "Resource": "arn:aws:execute-api:us-east-2:AccountId:API_Id/*"
      }
    ]
   },
   "principalId": null
  }

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

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