0
0

【SAM】APIGatewayのオーソライザーによる認証をAPIごとに個別設定する

Posted at

やりたいこと

APIGatewayでオーソライザーを設定しているが、一部のAPIでは認証が不要なのでオーソライザーを通さずに処理を実行できるようにしたい。

最終的なコード

Api:
    Type: AWS::Serverless::Api
    Properties:
    Auth:
        DefaultAuthorizer: CognitoAuthorizer        
        Authorizers:
          CognitoAuthorizer:            
            UserPoolArn:
              Fn::GetAtt:
                - CognitoUserPool
                - Arn
            Identity:
              Header: Authorization
(中略)
SigninFunction:
    Type: AWS::Serverless::Function
      Events:
        SigninApi:
          Type: Api
          Properties:
            Path: /signin
            Method: post
            RestApiId:
              Ref: Api
            Auth:
              Authorizer: NONE # これで無効化
              OverrideApiAuth: true # これを指定しないと上書きされない

解決までに試したこと

まずはオーソライザーを下記のように設定した

Api:
    Type: AWS::Serverless::Api
    Properties:
    Auth:
        DefaultAuthorizer: CognitoAuthorizer        
        Authorizers:
          CognitoAuthorizer:            
            UserPoolArn:
              Fn::GetAtt:
                - CognitoUserPool
                - Arn
            Identity:
              Header: Authorization

ここでDefaultAuthorizerを指定することで全てのAPIでこのオーソライザーで認証チェックが実施されるようになる。

このままだとサインインのような認証が必要のないAPIでも認証チェックが実施されてしまうので下記のように設定をした。

SigninFunction:
    Type: AWS::Serverless::Function
      Events:
        SigninApi:
          Type: Api
          Properties:
            Path: /signin
            Method: post
            RestApiId:
              Ref: Api
            Auth:
              Authorizer: NONE

Authの部分でAuthorizer: NONEとすることでデフォルトのオーソライザーを無効化して、認証チェックなしでAPIが実行されるはず・・・と思ったが、これだと認証チェックが実行されてしまい、401が返ってしまった。

スクリーンショット 2023-12-19 23.13.20.png

改めてリファレンスを調べると、下記のような記述を発見

AWS::Serverless::Api リソースの DefinitionBody プロパティを使用して API を記述する場合は、Authorizer で OverrideApiAuth を使用してグローバルオーソライザーをオーバーライドする必要があります。詳細については、「OverrideApiAuth」を参照してください。

ということで、下記のようにOverrideApiAuthをtrueに設定した。

SigninFunction:
    Type: AWS::Serverless::Function
      Events:
        SigninApi:
          Type: Api
          Properties:
            Path: /signin
            Method: post
            RestApiId:
              Ref: Api
            Auth:
              Authorizer: NONE
              OverrideApiAuth: true

これで無事に認証無しで実行できるようになった

スクリーンショット 2023-12-19 23.18.46.png

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