👤

[AWS congito × NestJS]ダミーのメアドでユーザー登録する方法

2025/02/02に公開

本来であれば有効なメアドでの登録が推奨されると思いますが、
例えばテスト環境用等、ダミーのメアドで登録したい場合があると思います。

しかし、ホストUIやAWSの管理画面経由でダミーのメアドでユーザーを登録しようとすると
どうしても有効なメアドが必要になるようです。(もし違ったらすみません。)

なのでcognitoのライブラリを活用して、NestJSでのサンプルの実装方法を記しておきます。

import { CognitoIdentityProvider } from '@aws-sdk/client-cognito-identity-provider';
import { ConfigService } from '@nestjs/config';

export class CreateUser {
  private userPoolId: string;

  constructor(private configService: ConfigService) {
    this.userPoolId = this.configService.get<string>('COGNITO_USER_POOL_ID') as string;
  }
  async execute() {
      const dummyEmail = 'dummy@email.com'
      const password = 'password'
      const cognito = new CognitoIdentityProvider({
        region: process.env.AWS_REGION as string,
        credentials: {
          accessKeyId: process.env.COGNITO_ACCESS_KEY_ID as string,
          secretAccessKey: process.env.COGNITO_SECRET_ACCESS_KEY as string,
        }
      });
      // ユーザー登録
      await cognito.adminCreateUser({
        UserPoolId: this.userPoolId,
        Username: dummyEmail,
        UserAttributes: [
          { Name: 'email', Value: dummyEmail },
        ],
        // 一括で50件以上登録する場合、上限に引っかかるため送信を取りやめるオプション
        MessageAction: 'SUPPRESS'
      })
      // パスワードを変更
      await cognito.adminSetUserPassword({
        UserPoolId: this.userPoolId,
        Username: dummyEmail,
        Password: password,
        Permanent: true,
      })
  }
}

以上です。
もし間違いがあればコメントをいただけると幸いです。

Discussion