在AWS API Gateway中如何更新API密钥的用法?

时间:2019-01-04 19:44:44

标签: aws-lambda aws-api-gateway aws-sdk-net

我已经使用.NET Core开发了自定义Lambda授权器。处理程序从Request对象获取API-KEY,然后执行以下操作:

1>确保API-KEY存在
2>通过ID获取使用计划
3>获取API密钥的当前用法
4> TODO:现在我想将API-KEY的剩余使用量减少1。有些事情我无法弄清
a)我如何从GetUsageResponse.Items中获得当前用法的价值
b)在PatchOperation中应使用哪些值来更新“用法”?

public async Task<APIGatewayCustomAuthorizerResponse> FunctionHandler(APIGatewayCustomAuthorizerRequest authEvent, ILambdaContext context)
{
     var key = authEvent.QueryStringParameters["key"];
     var isAuthorized = CheckAuthorization(key);            
     var authPolicy = CreateAuthPolicy(isAuthorized);
     return authPolicy;
}

private async Task<bool> CheckAuthorization(string key)
{
    var client = new Amazon.APIGateway.AmazonAPIGatewayClient();            
    var response = await client.GetApiKeysAsync(new GetApiKeysRequest()
    {
        IncludeValues = true
    });   
    var apiKey = response.Items.SingleOrDefault(x => x.Value == key);
    if (apiKey == null)
    {
        return false;
    }

    // Get Usage Plan
    var usagePlan = await client.GetUsagePlanAsync(new GetUsagePlanRequest()
    {
        UsagePlanId = "myUsagePlanID"
    });               

    //Get API-KEY's Usage for current month
    var usage = await client.GetUsageAsync(new GetUsageRequest()
    {
        KeyId = apiKey.Id,
        UsagePlanId = "myUsagePlanID",
        StartDate = "2019-01-01",
        EndDate = "2019-01-31"
    });

    //TODO a)how do i get value of the current usage from `usage.Items`
    //TODO b) what values should go in PatchOperation to update Usage?
    var operations = new List<PatchOperation>();
    var operation = new PatchOperation()
    {
        From ="???",
        Op = "????",
        Path = "????",
        Value ="????"
    };
    operations.Add(operation);           

    await client.UpdateUsageAsync(new UpdateUsageRequest()
    {
        KeyId = apiKey.Id,
        UsagePlanId = "myUsagePlanID",
        PatchOperations = operations
    });           

    return true;
}

0 个答案:

没有答案