Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CognitoのLambdaトリガーで認証処理をカスタマイズ!

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
Avatar for sasayan sasayan
August 06, 2026
38

 CognitoのLambdaトリガーで認証処理をカスタマイズ!

Avatar for sasayan

sasayan

August 06, 2026

Transcript

  1. Lambdaトリガーとは トリガー名 Pre sign-up Post confirmation Pre authentication Post authentication

    Define auth challenge Create auth challenge Verify auth challenge response Pre token generation User migration Custom message Custom email sender Custom SMS sender Inbound federation 概要 ユーザー登録の直前に、登録可否の判定や自動確認を行う ユーザー登録やパスワードリセットの確認完了後に処理を行う 認証処理の直前に、ログイン可否を判定する 認証成功後に、ログ記録や外部システム連携を行う カスタム認証で、次に実行する認証チャレンジを決定する カスタム認証で、質問や認証コードなどのチャレンジを生成する カスタム認証で、ユーザーの回答が正しいか判定する トークン発行前に、ID・アクセストークンのクレームを編集する ログイン時などに、既存のユーザー管理基盤からユーザーを移行する Cognitoが送信するメールやSMSの件名・本文を変更する Cognitoの代わりに、Lambdaからメールを送信する Cognitoの代わりに、LambdaからSMSを送信する 外部IdPから受け取ったユーザー属性を、Cognitoへの反映前に変換する
  2. Lambdaトリガーとは トリガー名 Pre sign-up Post confirmation Pre authentication Post authentication

    Define auth challenge Create auth challenge Verify auth challenge response Pre token generation User migration Custom message Custom email sender Custom SMS sender Inbound federation 概要 ユーザー登録の直前に、登録可否の判定や自動確認を行う ユーザー登録やパスワードリセットの確認完了後に処理を行う 認証処理の直前に、ログイン可否を判定する 認証成功後に、ログ記録や外部システム連携を行う カスタム認証で、次に実行する認証チャレンジを決定する カスタム認証で、質問や認証コードなどのチャレンジを生成する カスタム認証で、ユーザーの回答が正しいか判定する トークン発行前に、ID・アクセストークンのクレームを編集する ログイン時などに、既存のユーザー管理基盤からユーザーを移行する Cognitoが送信するメールやSMSの件名・本文を変更する Cognitoの代わりに、Lambdaからメールを送信する Cognitoの代わりに、LambdaからSMSを送信する 外部IdPから受け取ったユーザー属性を、Cognitoへの反映前に変換する
  3. Pre sign-up ユーザー登録の直前に、登録可否の判定や自動確認を行う ➀特定のドメインのみ登録許可する 社内メールアドレスのみ許可し、それ以外は拒否する def lambda_handler(event, context): email =

    event["request"]["userAttributes"].get("email", "") if not email.endswith("@example.co.jp"): raise Exception("会社のメールアドレスを使用してください")
  4. Pre sign-up ②ValidationDataが利用できる サインアップ処理中のみ利用できる一時情報の参照 例:招待コードを用いたサインアップ def lambda_handler(event, context): code =

    event["request"]["validationData"].get("code", "") if not isinstance (code, 123456): raise Exception("招待コードを入力して下さい")
  5. Post confirmation ユーザー登録完了後に処理を行う(ユーザーの操作に依存しない) ・SQS経由で業務用DBに登録 def lambda_handler(event, context): attributes = event["request"]["userAttributes"]

    sqs.send_message( QueueUrl=os.environ["QUEUE_URL"], MessageBody=json.dumps({ "userId": attributes["sub"], "email": attributes.get("email") }) ) Lambdaトリガーは5秒以内 に応答する必要あり。
  6. Pre authentication 認証処理の直前に、ログイン可否を判定する ・ステータスによるログイン可否判定 def lambda_handler(event, context): user_id = event["request"]["userAttributes"]["sub"]

    result = table.get_item( Key={"userId": user_id} ) user = result.get("Item") if not user or user.get("status") == "STOP": raise Exception("このユーザーは利用停止中です")
  7. Pre token generation ②アクセストークンのスコープを追加・削除し、細かい認可を行う 例:担当者は参照のみ、リーダーは編集可能 def lambda_handler(event, context): role =

    event["request"]["userAttributes"].get( "custom:role", "maintenance" ) scopes_to_add = ["system.read"] scopes_to_suppress = [] if role == "leader": scopes_to_add.append("system.write") else: scopes_to_suppress.append("system.write") event["response"]["claimsAndScopeOverrideDetails"] = { "accessTokenGeneration": { "claimsToAddOrOverride": { "application_role": role }, "scopesToAdd": scopes_to_add, "scopesToSuppress": scopes_to_suppress } }
  8. Custom message Cognitoが送信するメールやSMSの件名・本文を変更する ・言語、ユーザー属性などに応じて内容を動的に変更 def lambda_handler(event, context): code = event["request"]["codeParameter"]

    language = event["request"]["userAttributes"].get( "custom:language", "ja" ) 同一トリガーで複数の利用ケース if event["triggerSource"] == "CustomMessage_SignUp": がある場合、条件分岐を行う if language == "en": event["response"]["emailSubject"] = ¥ "Confirm your account" event["response"]["emailMessage"] = ¥ f"Your confirmation code is {code}." else: event["response"]["emailSubject"] = ¥ "アカウント登録の確認" event["response"]["emailMessage"] = ¥ f"確認コードは {code} です。"