首页 > 解决方案 > AWS API Gateway:如何为我的用户生成 apiKey 并让他们将其包含在查询参数中?

问题描述

目标:我们只想让我们的客户使用我们的 HTTP 端点,首先生成一个 APIkey,然后将其传递到请求 URI 参数中以触发 lambda 函数。

我尝试了什么:不确定如何以编程方式生成 apiKey。决定用我在 API Gateway 中找到的 apiKey 进行测试,并在 Lambda 函数中编写了以下代码:

exports.handler = async (event, context, callback) => {
   const apikey =
      event.queryStringParameters.apikey || event.stageVariables.apikey;

  const tmp = event.methodArn.split(":");
  const apiGatewayArnTmp = tmp[5].split("/");
  const awsAccountId = tmp[4];
  const region = tmp[3];
  const restApiId = apiGatewayArnTmp[0];
  const stage = apiGatewayArnTmp[1];

  callback(null, {
      principalId: "principalId",
      policyDocument: {
          Version: "2012-10-17",
          Statement: [
              {
                  Action: "execute-api:Invoke",
                  Effect: "Allow",
                  Resource: `arn:aws:execute-api:${region}:${awsAccountId}:${restApiId}/${stage}/*/*`
              }
          ]
      },
      usageIdentifierKey: apikey
  });

  return context.succeed('Success!');
};

在 API Gateway 中,我还添加了一个带有 request querystring 的自定义授权者apikey

当我单击测试并为键查询字符串传递任何字符串值时,apikey我得到 200OK 并显示以下内容:

Response
Response Code: 200
Latency 2607
Policy
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "execute-api:Invoke",
      "Effect": "Allow",
      "Resource": "arn:aws:execute-api:us-west-2:2234235234:asdf3r3r/ESTestInvoke-stage/*/*"
    }
  ]
}

当我打开时,https://s9fs7h0.execute-api.us-west-2.amazonaws.com/default/executeWSL?apikey=myAPIkeygoeshere我仍然得到{"message":"Forbidden"}

我哪里做错了?我预计导航该 URL 会返回Success!

标签: aws-lambdaaws-api-gateway

解决方案


推荐阅读