简体   繁体   中英

API Gateway - Custom Authorizer was not working

I have run into some trouble configuring/using Authentication on 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:

{
"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. 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).

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":

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

.Net Core (C#) version of Custom Authorizer

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
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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