0
0

SAMでAPI Gateway AuthorizerをプリフライトリクエストのOPTIONSメソッド時に除外する方法

Posted at

はじめに

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リソースをコンソール上で確認してみます。

image.png
GET リクエストには認可設定が適用されています。

image.png
OPTIONS リクエストでは、認可設定がNONEになっています。無事に除外できたようです。

おわりに

以上、SAMでAPI Gateway AuthorizerをプリフライトリクエストのOPTIONSメソッド時に除外する方法についてまとめました。

参考記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0