

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 的 API 密钥示例 AWS SAM
<a name="serverless-controlling-access-to-apis-keys"></a>

您可以 APIs 通过在 AWS SAM 模板中要求 API 密钥来控制对您的访问权限。为此，您需要使用 [ApiAuth](sam-property-api-apiauth.md) 数据类型。

以下是 API 密钥的示例 AWS SAM 模板部分：

```
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        ApiKeyRequired: true # sets for all methods

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: .
      Handler: index.handler
      Runtime: nodejs12.x
      Events:
        ApiKey:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /
            Method: get
            Auth:
              ApiKeyRequired: true
```

有关 API 密钥的更多信息，请参阅*《API Gateway 开发人员指南》*中的[创建和使用带 API 密钥的使用计划](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-usage-plans.html)。