Lambda オーソライザーのサンプル。
SAMなので
sam build
sam deploy --guided # --guidedは最初の1回
OutputのHelloApiのURLに対してcurlでアクセスする。
/hello/は Auth:ヘッダに allow
で認証される。
curl -H "Auth: allow" https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hello/
テストのためにToken Sourceをデフォルトの"Authorization"から"Auth"に変えてある。(スペルもめんどくさいし)
/goodbye/は認証不要
curl https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/goodbye/
Authorizer: NONE
で
デフォルトオーソライザーを無効化するテスト。
/basic/はBASIC認証
curl -u admin:password https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/basic/
通常だと WWW-Authenticate: ヘッダが返せないのでブラウザで使えないが
Gateway Responsesをカスタマイズして、
WWW-Authenticate: Basic realm=xxxxx
を返すようにしたのでブラウザで試してみてください。
ただし副作用として/hello/まで
WWW-Authenticate: Basic
が帰ってるので、ごめんなさい。
クエリauthにallowを渡す
curl https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hi?auth=allow
# or
curl -G --data-urlencode "auth=allow" https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/Prod/hi
sam delete
- LambdaTokenAuthorizer - AWS Serverless Application Model
- LambdaTokenAuthorizationIdentity - AWS Serverless Application Model
- API Gateway Lambda オーソライザーを使用する - Amazon API Gateway
LambdaTokenAuthorizationIdentityの Header: に対するドキュメントが無い (けど動くし、設定できてコンソールからも見える)。
同様に Token Validationに指定できるのは正規表現らしいけど、 ドキュメントが見つからない。
- カスタマイズされたレスポンスの例 - AWS Serverless Application Model
- Using Basic Authentication with AWS API Gateway and Lambda - Cloudmailin
Token Validationを有効にすると、 Custom Gateway Responsesが効かなくなる...
Lambdaオーソライザーは昔は「カスタムオーソライザー」と呼ばれていたらしい。
authのlambdaは非同期ハンドラ(non-async handler)で書かないといけないものなの?
non-async handlerのcallbackは
callback(response_error, response_success)
らしいのだけど、ドキュメントが見つからない。
auth関数でprincipalIdには何を設定するべき?
principalId 値には、マッピングテンプレートで $context.authorizer.principalId 変数を使ってアクセスできます。これはバックエンドに値を渡す場合に便利です。
引用元: [Amazon API Gateway Lambda オーソライザーからの出力 - Amazon API Gateway](https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/ api-gateway-lambda-authorizer-output.html)
後段のlambdaで使えるよう渡すだけ。
同様に、policyのcontextで設定した値は 後段のlambdaで event.requestContext.authorizer から取れる。