Amazon Cognito User Poolsを使って、webサイトにユーザ認証基盤を作る - Qiita
[新機能] Amazon Cognito に待望のユーザー認証基盤「User Pools」が追加されました! | Developers.IO
とかを見ていて、とりあえず扱えるようになりたいと思ったのでざっと触ってみました。
ファイルのダウンロード
必要なファイルをDLします。
横着仕様なので、404エラーになった場合は元リポジトリからzipファイルをDLしましょう。
# https://github.com/aws/amazon-cognito-identity-js
$ wget https://raw.githubusercontent.com/aws/amazon-cognito-identity-js/master/dist/aws-cognito-sdk.min.js
$ wget https://raw.githubusercontent.com/aws/amazon-cognito-identity-js/master/dist/amazon-cognito-identity.min.js
# https://github.com/aws/aws-sdk-js
$ wget https://sdk.amazonaws.com/js/aws-sdk-2.4.10.min.js
# http://momentjs.com/
$ wget http://momentjs.com/downloads/moment.min.js
htmlファイルを準備する
<!DOCTYPE html>
<html>
<head>
<title>Cognito User Pools Test page</title>
</head>
<body>
<script src="js/aws-cognito-sdk.min.js"></script>
<script src="js/amazon-cognito-identity.min.js"></script>
<script src="js/aws-sdk-2.4.10.min.js"></script>
<script src="js/moment.min.js"></script>
<script>
//ここにコードを書く
</script>
</body>
</html>
サンプルコードを突っ込む
https://github.com/aws/amazon-cognito-identity-js#usage のコードを動かしてみます。
先ほどのコードの//ここにコードを書く
部分に突っ込んでみましょう。
AWS.config.region = 'us-east-1'; // Configure region in the AWS SDK if you will use it
AWSCognito.config.region = 'us-east-1'; //This is required to derive the endpoint
// Need to provide placeholder keys unless unauthorised user access is enabled for user pool
AWSCognito.config.update({
accessKeyId: 'anything',
secretAccessKey: 'anything'
})
var poolData = {
UserPoolId : 'us-east-1_TcoKGbf7n',
ClientId : '4pe2usejqcdmhi0a25jp4b5sh3'
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var attributeList = [];
var dataEmail = {
Name : 'email',
Value : 'email@mydomain.com'
};
var dataPhoneNumber = {
Name : 'phone_number',
Value : '+15555555555'
};
var attributeEmail = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail);
var attributePhoneNumber = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataPhoneNumber);
attributeList.push(attributeEmail);
attributeList.push(attributePhoneNumber);
userPool.signUp('username', 'password', attributeList, null, function(err, result){
if (err) {
alert(err);
return;
}
cognitoUser = result.user;
console.log('user name is ' + cognitoUser.getUsername());
});
AWSCognito.config.update
へのクレデンシャルの設定と、poolData
に作成したCognito User Poolsの情報を入れるようにしましょう。設定していないと400エラーになります。
動作結果
先ほどのhtmlファイルをブラウザから開けばJSが実行されます。
アラートウィンドウが出なければ登録完了(のはず)です。
触ってみて
「簡単や」「簡単や」ととある人がしきりに言っていましたが、本当にお手軽ですね。
まだユーザー登録しただけですので、いろいろ触ってみて会員サイトのようなもの作れたらいいなと思います。