はじめに
ここでは、Amazon Cognito を使用して、メールアドレスとパスワードを登録するためのソースコードを書きます。ただし、既にユーザープールを作成し、ユーザープールにアプリを追加ているものとします。
AWS Amplify ライブラリをインストール
Amazon Cognito を使用するには、AWS Amplify ライブラリが必要なのでインストールします。
$ npm install aws-amplify --save
ちなみに 「Amazon Cognito ID SDK for JavaScript」が「AWS Amplify ライブラリ」 の一部になったらしいです。
ソースコードに次の記述を書きます。HTML は省略します。
import * as AmazonCognitoIdentity from "amazon-cognito-identity-js";
export default class UserRegistration {
// フォームの登録ボタンをクリックした時にこれを呼び出す。
public registerUser() {
let poolData = {
UserPoolId: <ユーザープールのID>,
ClientId: <アプリクライアントID>
};
let userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
let email = {
Name: "email",
Value: <ユーザーが入力したメールアドレス>
};
let attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(
email
);
userPool.signUp(
<ユーザーが入力したメールアドレス>,
<ユーザーが入力したパスワード>,
[attributeEmail],
[],
(err, result) => {
if (!err) {
// 成功した場合の処理。
} else {
// 失敗した場合の処理。
}
}
);
}
}
ユーザーのメールアドレスとパスワードをフォームから取得して、Cognito に送信します。
これで、フォームの登録ボタンなどをクリックした時に registerUser() を実行すると、ユーザーが入力したメールアドレスに確認コードが届きます。次は、確認コードを Cognito に送信しなければなりません。
メールアドレスの確認を行うためのソースコードが以下です。
import * as AmazonCognitoIdentity from "amazon-cognito-identity-js";
export default class EmailVerification {
public verifyEmail() {
let poolData = {
UserPoolId: <ユーザープールのID>,
ClientId: <アプリクライアントID>
};
let userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
this.createCognitoUser(userPool).confirmRegistration(
<ユーザーが入力した確認コード>,
true,
(err, result) => {
if (!err) {
// 成功した時の処理。
} else {
// 失敗した時の処理。
}
}
);
}
private createCognitoUser(userPool) {
return new AmazonCognitoIdentity.CognitoUser({
Username: <メールアドレス>,
Pool: userPool
});
}
}
ユーザーが入力した確認コードをフォームから取得し、Cognito に送信しています。
参考資料
以下を参考にしてソースコードを書きました。
・https://aws.amazon.com/jp/getting-started/projects/build-serverless-web-app-lambda-apigateway-s3-dynamodb-cognito/module-1/
・https://github.com/aws-samples/aws-serverless-workshops/tree/master/WebApplication/1_StaticWebHosting/website