0

In AWS API Gateway I am developing lambda function for custom authorizer using .NET Core. The API will receive api-key in query string and my custom authroizer will validate the key. Based on my understanding, after validation is done the lambda function needs to return IAM policy. The awslab blurprint does not have any example for .NET core. The only example i found so far is GrandmasRecipes that is using JWT Token.

I would like to know what IAM policy the lambda function needs to return and are there any corresponding .NET Core classes for request and response?

Update 1
So below is my code for custom lambda authorizer. However i would like know:

1> What should be PrincipalID. Currently i am just setting it to User

2>CheckAuthorization method gets all the keys from aws and only check the existence by comparing the key from the request. It should also check the Usage Plans and make sure the key from the request is configured in Usage Plans

3>The role that this Authorizer is executing under is attached to AmazonAPIGatewayAdministrator policy so that it can get API Keys, whats the minimum policy do i need for this role to validate api-key?

4>Is there any in-built method in AWSSDK to do validate api-key correctly?

[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace ApikeyAuthorizer
{
    public class Function
    {
        public async Task<APIGatewayCustomAuthorizerResponse> FunctionHandler(APIGatewayCustomAuthorizerRequest authEvent, ILambdaContext context)
        {
            var key = authEvent.QueryStringParameters["key"];
            bool authorized = await CheckAuthorization(key);

            var authPolicy = new APIGatewayCustomAuthorizerResponse();
            authPolicy.PrincipalID = "user";
            authPolicy.PolicyDocument = new APIGatewayCustomAuthorizerPolicy();
            authPolicy.PolicyDocument.Version = "2012-10-17";
            authPolicy.PolicyDocument.Statement = new List<APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>();
            if (authorized)
            {
                var statement = new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement();
                statement.Action = new HashSet<string>(new string[] { "execute-api:Invoke" });
                statement.Effect = "Allow";
                statement.Resource = new HashSet<string>(new string[] { "arn:aws:execute-api:us-east-1:xxxxx:*/*/GET/*" });
                authPolicy.UsageIdentifierKey = key;
                authPolicy.PolicyDocument.Statement.Add(statement);
            }
            else
            {
                var statement = new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement();
                statement.Action = new HashSet<string>(new string[] { "execute-api:Invoke" });
                statement.Effect = "Deny";
                statement.Resource = new HashSet<string>(new string[] { "arn:aws:execute-api:us-east-1:xxxxx:*/*/GET/*" });
                authPolicy.PolicyDocument.Statement.Add(statement);
            }

            return authPolicy;
        }

        public async Task<bool> CheckAuthorization(string key)
        {            
            Amazon.APIGateway.AmazonAPIGatewayClient client = new Amazon.APIGateway.AmazonAPIGatewayClient();
            var response = await client.GetApiKeysAsync(new Amazon.APIGateway.Model.GetApiKeysRequest()
            {
                IncludeValues = true
            });           

            foreach (var apiKey in response.Items)
            {               
                if (apiKey.Value == key)
                {             
                    return true;
                }
            }           
            return false;
        }
    }
}
LP13
  • 30,567
  • 53
  • 217
  • 400

2 Answers2

2

You don't need to use a Lambda Authorizer to validate API Key neither it should be used for authorisation. You can do following to configure API key validation in API Gateway.

  1. In you API Resources section, set API Key Required true for the methods where you want to enable it
  2. Go to API Keys section, select Create API key from Actions dropdown and create a key
  3. Go to Usage Plans section and create a new usage plan.
  4. After you've created a usage plan click on it and then click API Keys tab. Here click Add API Key to Usage Plan and add the key you created in step # 2
  5. Now click on Details tab then click Add API Stage. Select your API and stage that you want to restrict with API Key.

Your API methods are now required an x-api-key HTTP header where you've enabled it. When you request API endpoint make sure you add x-api-key header with same value you have created in step 2 above. If you don't add this header or put a wrong value you will get 403 Forbidden error.

A.Khan
  • 3,826
  • 21
  • 25
1
curl -X PUT \
https://XXXX.XXXXX-api.ca-central-1.amazonaws.com/PROD/XXX-microservice \
 -H 'Content-Type: application/json' \
 -H 'x-api-key: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' \
 -d '{

 "initData": "HI",
 "name": "vaquar khan",
 "likes": "Java"
}'

Security key validation taken care by API getaway so no lambda authorizer required

Please dont create duplicate question just update old queston ,I have answred in your question here : - How to validate API Key in AWS Lambda function

vaquar khan
  • 10,864
  • 5
  • 72
  • 96