はじめに
LambdaのトリガーとしてAPI Gatewayを指定し、すべてのリソースに一括でAuthorizerを設定したところ、OPTIONSリクエストにもAuthorizerが設定されてしまい、通信に失敗してしまいました。日本語で解説記事がなかったため執筆することにしました。
対象者
この記事は下記のような人を対象にしています。
- APIをSAMを使ってLambdaにデプロイしようとしている人
- Lambda Authorizerを使用してAPI Gatewayに認証をかけたい人
前提知識
結論
下記の通り、 AddDefaultAuthorizerToCorsPreflight: False
を記載します。
CognitoAuthorizerを例に挙げていますが、IAMでも同様です。
template.yaml
Parameters:
UserPoolArn:
Type: String
Description: replace
Resources:
SampleApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Auth:
DefaultAuthorizer: CognitoAuthorizer
Authorizers:
CognitoAuthorizer:
UserPoolArn: !Ref UserPoolArn
AddDefaultAuthorizerToCorsPreflight: False // この記述でPreflight requestの認証を除外
SampleFunction:
Type: AWS::Serverless::Function
Properties:
PackageType: Image
Events:
Sample:
Type: Api
Properties:
Path: /hello
Method: get
RestApiId: !Ref SampleApi
デプロイ後のAPI Gatewayリソースをコンソール上で確認してみます。
OPTIONS リクエストでは、認可設定がNONEになっています。無事に除外できたようです。
おわりに
以上、SAMでAPI Gateway AuthorizerをプリフライトリクエストのOPTIONSメソッド時に除外する方法についてまとめました。