やりたいこと
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が返ってしまった。
改めてリファレンスを調べると、下記のような記述を発見
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
これで無事に認証無しで実行できるようになった