介绍
Amazon Web Services (AWS) 提供了一款服务,即 API 网关(API Gateway)。该服务可以让开发者轻松地创建、发布、维护、监控和安全地管理 API。API Gateway 可以与其他 AWS 服务集成,例如 AWS Lambda、Amazon S3、Amazon DynamoDB 等。API Gateway 还提供了开发者工具、面向服务的架构(SOA)等高级功能。
在使用 AWS API Gateway 时,需要为 API 资源授权,以确定哪些客户端和用户可以访问 API。 在这类场景中,AWS 已经为我们提供了一个快速生成策略的工具 - aws-api-gateway-policy-generator。
aws-api-gateway-policy-generator 是一个 npm 包,它封装了 AWS API Gateway 的授权策略生成器,使得开发者可以快速生成出定义好的 api 访问策略,并且可以使用 Node.js 代码实现对 AWS 服务的访问控制功能。
安装
您可以通过 npm(Node.js 包管理器)将 aws-api-gateway-policy-generator 添加到您的项目中:
npm install aws-api-gateway-policy-generator
使用示例
-- -------------------- ---- ------- ----- --- - ------------------- ----- -------------- - -------------------------------------------- --------------- - ----- ------- -------- -- - --- - ----- ------ - --------------------------- ----- ----- - ---------- ----- ------ - ---------- ----- --------- - ----------------------------- -- ---- ----- --------- - --------------- -------------------- ----- -------- - --- - ----------- -- ----------------------------------- ----- ------ - ----- --------------------------------------------------- ---------- ------- ---------- ------ ------- - ----- ----- - ----------------- ------ - ----------- ---- ----- ---------------- -------- -------------- --- -- - --
使用教程
首先请安装 aws-api-gateway-policy-generator npm 包。
npm install aws-api-gateway-policy-generator
在您的应用程序中引入 npm 包和 AWSSDK。
在这个例子中,我们将使用 Lambda 服务:
const AWS = require('aws-sdk'); const generatePolicy = require('aws-api-gateway-policy-generator');
在 Lambda 函数的入口中,解析
event.methodArn
并用它来生成 API Gateway 针对特定资源的 ARN。通过解析event.headers
中的AccountId
来动态地将云资源的访问权限授予特定帐户。const apiArn = event.methodArn.split('/'); const apiId = apiArn[1]; const region = apiArn[3]; const accountId = event.headers['x-account-id'] || '*'; const restApiId = apiId.substr(0, apiId.indexOf('-')); const resource = '/' + (event.path || '').split('/').splice(1).join('/');
在 API Gateway 中,资源(即路径)是与特定 API 关联的 URL 路径。我们将第一个路径元素删除并使用其余路径元素作为资源标识符。
生成 API Gateway 授权策略。
包
aws-api-gateway-policy-generator
提供了一个异步函数generatePolicyForEndpoint()
,其中包含许多输入参数来动态控制策略生成的相关信息。例如,最基本的策略生成可以使用以下代码来启动:
const policy = await generatePolicy.generatePolicyForEndpoint(accountId, restApiId, region, resource);
策略生成器已支持的更详细的用法已经在源代码中设有详细文档,您可以通过 VSCode 等单元测试工具的代码提示功能查看相应文档。
将策略返回给 API Gateway。
在此处,策略可以直接以 JSON 格式返回到 API Gateway,因为
AWS Lambda
会自动将策略信息解析并渲染到响应中。return policy;
总结
aws-api-gateway-policy-generator
是一个方便的 npm 包,它封装了 API Gateway 的授权策略生成器,使得开发者可以快速生成 api 访问策略,并且可以使用 Node.js 代码实现对 AWS 服务的访问控制功能。 请尽快将其添加到您的项目中,以提高您项目的可维护性和改进基于 Serverless 架构的应用。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/60056cbe81e8991b448e632d