在AWS API Gateway中,我正在使用.NET Core为自定义授权者开发lambda函数。该API将在查询字符串中接收api-key,而我的自定义身份验证器将验证该密钥。根据我的理解,验证完成后,lambda函数需要返回IAM policy。 awslab blurprint没有用于.NET Core的任何示例。到目前为止,我发现的唯一示例是使用JWT令牌的GrandmasRecipes。
我想知道lambda函数需要返回什么IAM
策略,并且是否存在用于请求和响应的相应.NET Core类?
更新1
因此,以下是我的自定义Lambda授权者代码。但是我想知道:
1>应该是PrincipalID
。目前,我只是将其设置为User
2> CheckAuthorization
方法从aws
获取所有密钥,并且仅通过比较请求中的密钥来检查是否存在。它还应检查Usage Plans
并确保在Usage Plans
3>此授权者在其下执行的角色已附加到AmazonAPIGatewayAdministrator
策略中,以便它可以获取API密钥,该角色验证api-key所需的最低策略是什么?
4> AWSSDK
中是否有任何内置方法可以正确验证api-key?
[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;
}
}
}
答案 0 :(得分:1)
您无需使用Lambda授权器来验证API密钥,也无需将其用于授权。您可以按照以下步骤在API网关中配置API密钥验证。
您的API方法现在是启用它的x-api-key HTTP标头。当您请求API端点时,请确保您添加的x-api-key
标头具有与上述步骤2中创建的相同的值。如果您不添加此标头或输入错误的值,则会收到403 Forbidden错误。
答案 1 :(得分:0)
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"
}'
API逍遥游玩会确保安全密钥验证,因此无需lambda 需要授权者
请不要创建重复的问题,只更新旧的问题,我在这里回答了您的问题: -How to validate API Key in AWS Lambda function