0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Dockerで構築する Cognito(moto) ローカル認証環境

Posted at

Dockerで構築する Cognito(moto) ローカル認証環境

AWS Cognito を利用したシステムでは、
認証周りの開発・テストで毎回AWSに接続するのがボトルネックになります。

本記事では moto を使って Cognito をローカルモック化 し、
クラウド接続不要で認証付き開発ができる環境を構築します。
さらに、ユーザー作成 → ログイン成功までの確認手順も紹介します。


🎯 この記事でできること

  • Cognito User Pool をローカルで再現
  • ユーザー作成
  • 認証(ログイン)成功確認
  • CI環境での認証テスト自動化
  • AWS課金ゼロの開発環境

🏗 構成イメージ

Backend API
   ↓
Cognito (moto mock)

🐳 docker-compose.yml

services:
  moto:
    build: ./moto
    ports:
      - "5000:5000"

🐳 motoコンテナ構築

moto/Dockerfile

FROM python:3.11

RUN pip install moto[server] boto3

WORKDIR /app
COPY init_cognito.py .

CMD moto_server cognito-idp -H 0.0.0.0 -p 5000 & \
    sleep 5 && \
    python init_cognito.py && \
    tail -f /dev/null

moto起動後にPythonスクリプトでUser PoolとApp Clientを作成します。


🔐 Cognito初期化スクリプト

import boto3

client = boto3.client(
    "cognito-idp",
    endpoint_url="http://moto:5000",
    region_name="ap-northeast-1",
    aws_access_key_id="dummy",
    aws_secret_access_key="dummy"
)

pool = client.create_user_pool(PoolName="local-user-pool")
pool_id = pool["UserPool"]["Id"]

app_client = client.create_user_pool_client(
    UserPoolId=pool_id,
    ClientName="local-client",
    GenerateSecret=False
)

print("User Pool:", pool_id)
print("Client ID:", app_client["UserPoolClient"]["ClientId"])

👤 テストユーザー作成 & ログイン確認

ユーザー作成

client.admin_create_user(
    UserPoolId=pool_id,
    Username="testuser",
    UserAttributes=[
        {"Name": "email", "Value": "test@example.com"},
        {"Name": "email_verified", "Value": "true"}
    ],
    TemporaryPassword="TempPass123!"
)

client.admin_set_user_password(
    UserPoolId=pool_id,
    Username="testuser",
    Password="Password123!",
    Permanent=True
)

ログイン実行

auth = client.admin_initiate_auth(
    UserPoolId=pool_id,
    ClientId=app_client["UserPoolClient"]["ClientId"],
    AuthFlow="ADMIN_NO_SRP_AUTH",
    AuthParameters={
        "USERNAME": "testuser",
        "PASSWORD": "Password123!"
    }
)

print("Login Success:", "AuthenticationResult" in auth)

出力例:

Login Success: True

これでローカル環境でのログイン成功が確認できます。


🔌 アプリ側接続例(Node.js)

const AWS = require("aws-sdk");

const cognito = new AWS.CognitoIdentityServiceProvider({
  endpoint: "http://localhost:5000",
  region: "ap-northeast-1",
  accessKeyId: "dummy",
  secretAccessKey: "dummy",
});

⚠️ ハマりポイント

症状 原因
接続エラー endpoint_url未指定
認証動かない region不一致
ログイン失敗 ClientId未使用
APIエラー moto未対応API使用

🧪 CIでの活用

services:
  moto:
    image: motoserver/moto
    ports:
      - 5000:5000

✨ この構成のメリット

  • AWS不要
  • 認証テスト自動化可能
  • チーム間で再現性が高い
  • 認証周りのバグを早期検出

🏁 まとめ

motoを活用することで、
Cognito依存の開発を完全ローカルで再現可能になりました。

ユーザー作成からログイン成功まで確認できるため、
認証を含むバックエンド開発の効率が大きく向上します。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?