LoginSignup
48
50

More than 5 years have passed since last update.

Amazon Cognito UserPools を JavaScript から使ってみる

Last updated at Posted at 2017-03-29

0.はじめに

AWS がサーバーレスで推奨しているサービスを、色々と使ってみます。
今回は、Amazon Cognito User Pools を JavaScript から使ってみます。

1.Amazon Cognito User Pool を作成する

Amazon Cognito の User Pool を作成する。

  1. Getting started - Amazon Cognito - Amazon Web Services へ遷移し、「Manage your User Pools」ボタンを押下
     
    • スクリーンショット 2017-03-28 16.25.38.png  
  2. 「Create User Pool」ボタンを押下
     
    • スクリーンショット 2017-03-28 16.25.46.png  
  3. 以下の項目を設定し、「Review defaults」ボタンを押下
    • Pool name : SmapleUserPool
       
    • スクリーンショット 2017-03-28 16.26.28.png  
  4. 左側ペインから「Attributes」を選択後、以下の項目を設定し、「Save Changes」ボタンを押下
    • email :  Required : □ Alias : ☑︎
    • phone number :  Required : □ Alias : ☑︎
    • ※メールでも電話番号でもログイン出来る様にしたかったので、この設定に。
       
    • スクリーンショット 2017-03-28 16.29.25.png  
  5. 左側ペインから「Verification」を選択後、以下の項目を設定し、「Create Role」ボタンを押下
    • Do you want to enable Multi-Factor Authentication (MFA)?
      • ◉ Optional
         
    • スクリーンショット 2017-03-28 16.29.54.png  
  6. SMS用のロールが作成されるので、「Save Changes」ボタンを押下
     
    • 67b3a54d-84f1-8969-aac1-bd81fb7d872b.png  
  7. 左側ペインから「Apps」を選択後、「Add an app」リンクをクリック
     
    • スクリーンショット 2017-03-28 16.30.29.png  
  8. 以下の項目を設定し、「Create app」ボタンを押下
    • App name : Cognito
    • Refresh token expiration (days) : 30 ※デフォルト
    • Generate client secret : □
      • ※JavaScript からの認証の際にあると邪魔みたいなので。
    • Enable sign-in API for server-based authentication (ADMIN_NO_SRP_AUTH) : ☑︎
    • Only allow Custom Authentication (CUSTOM_AUTH_FLOW_ONLY) : □
       
    • スクリーンショット 2017-03-28 16.30.42.png  
  9. App が作成されるので、「Save Changes」ボタンを押下
     
    • スクリーンショット 2017-03-28 16.30.51.png  
  10. 「Create Pool」ボタンを押下
     
    • スクリーンショット 2017-03-28 16.31.17.png

2.Amazon Cognito Identity Pool を作成する

Amazon Cognito の Identity Pool を作成する。

  1. Getting started - Amazon Cognito - Amazon Web Services へ遷移し、「Manage Federated Identities」ボタンを押下
     
    • スクリーンショット 2017-03-29 13.12.01.jpg  
  2. 「Create new identity pool」ボタンを押下
     
    • スクリーンショット 2017-03-29 13.12.11.jpg  
  3. 以下の項目を設定し、「Create Pool」ボタンを押下
    • Identity pool name : SampleIdentityPool
    • Unauthenticated identities
      • Enable access to unauthenticated identities : ☑︎
    • Authentication providers
      • Cognito
        • User Pool ID : [Amazon Cognito User Pool の Pool Id]
        • App Client ID : [Amazon Cognito User Pool の App Client Id]
           
    • スクリーンショット 2017-03-29 13.13.29.jpg  
  4. 以下の項目を設定し、「許可」ボタンを押下
     
    • スクリーンショット 2017-03-29 13.15.06.jpg  
    • スクリーンショット 2017-03-29 13.15.52.jpg

3.S3 に静的ウェブサイトを構築する。

  1. 以下のサイトを参考に、S3 に静的ウェブサイトを構築する。

4.JavaScript からのサインアップ

  1. 「3.S3 に静的ウェブサイトを構築する。」で構築した S3 上に js フォルダを作成し、そこに以下の js ファイルを格納する。
  2. 以下の html ファイルを、「3.S3 に静的ウェブサイトを構築する。」で構築した S3 上に格納する。その際、以下の修正を忘れないこと。
    • 36,38 行目の [Amazon S3 Bucket Name]
    • 45 行目の [Amazon Cognito Identity Pool の Identity Pool Id]
    • 48 行目の [Amazon Cognito User Pool の Pool Id]
    • 49 行目の [Amazon Cognito User Pool の App Client Id]
signup.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8" />
    <title>Sign Up</title>
    <!-- AWS SDK //-->
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.23.0.min.js"></script>
    <!-- Amazon Cognito //-->
    <script src="js/jsbn.js"></script>
    <script src="js/jsbn2.js"></script>
    <script src="js/sjcl.js"></script>
    <script src="js/aws-cognito-sdk.min.js"></script>
    <script src="js/amazon-cognito-identity.min.js"></script>
    <!-- jquery //-->
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <!-- bootstrap3 //-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <form class="form-signup">
            <h2 class="form-signup-heading">Sign Up</h2>
            <div id="message" class="alert" style="display:none;"></div>
            <label id="labelUsername">UserID</label><br>
            <input type="text" id="inputUsername" class="form-control" placeholder="UserID" required autofocus></input>
            <label id="labelEmail">Email</label><br>
            <input type="text" id="inputEmail" class="form-control" placeholder="Email" required autofocus></input>
            <label id="labelPassword">Password</label><br>
            <input type="password" id="inputPassword" class="form-control" placeholder="Password" required></input>
            <p></p>
            <input type="button" class="btn btn-lg btn-primary btn-bloc" id="sign_up_btn" value="Sign Up"></input>
            <p></p>
            <a href="http://[Amazon S3 Bucket Name].s3-website-ap-northeast-1.amazonaws.com/signin.html" target="_blank">SignIn</a>
            <p></p>
            <a href="http://[Amazon S3 Bucket Name].s3-website-ap-northeast-1.amazonaws.com/activation.html" target="_blank">Activation & Forget Password</a>
        </form>
    </div>
    <script>
        // Initialize the Amazon Cognito credentials provider
        AWSCognito.config.region = "ap-northeast-1";
        AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId: "[Amazon Cognito Identity Pool の Identity Pool Id]"
        });
        var data = {
            UserPoolId: "[Amazon Cognito User Pool の Pool Id]",
            ClientId: "[Amazon Cognito User Pool の App Client Id]"
        };
        var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data);
        var attributeList = [];
        var cognitoUser;

        function uuid() {
            var uuid = "", i, random;
            for (i = 0; i < 32; i++) {
                random = Math.random() * 16 | 0;
                if (i == 8 || i == 12 || i == 16 || i == 20) {
                    uuid += "-"
                }
                uuid += (i == 12 ? 4 : (i == 16 ? (random & 3 | 8) : random)).toString(16);
            }
            return uuid;
        }

        $("#sign_up_btn").click(function() {
            username = $("#inputUsername").val();
            //username = uuid();
            email = $("#inputEmail").val();
            password = $("#inputPassword").val();
            if(!username) {
                $("#message").text("Input UserID !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            if(!email) {
                $("#message").text("Input Email !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            if(!password) {
                $("#message").text("Input Password !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            var dataEmail = {
                Name : "email",
                Value : email
            };
            var attributeEmail = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail);
            attributeList.push(attributeEmail);
            //var dataPhoneNumber = {
            //    Name : "phone_number",
            //    Value : '+81' + email
            //};
            //var attributePhoneNumber = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataPhoneNumber);
            //attributeList.push(attributePhoneNumber);
            userPool.signUp(username, password, attributeList, null, function(err, result){
                if (err) {
                    console.log(err);
                    $("#message").text(err);
                    $("#message").addClass("alert-danger");
                    $("#message").show();
                } else {
                     var url = "activation.html";
                     $("form").fadeOut(100, function(){
                        $(location).attr("href", url);
                     });
                     $(".wrapper").addClass("form-success");
                }
            });
        });

    </script>
</body>
</html>

 
3. サイトへアクセスすると、以下の画面が表示されるので、適当な値を入力し、「Sign Up」ボタンを押下
 
スクリーンショット 2017-03-29 14.40.11.jpg
 
4. 入力したメールアドレスへ、アクティベーションコードが送られてくる。

5.JavaScript からのアクティベーション

  1. 以下の html ファイルを、「3.S3 に静的ウェブサイトを構築する。」で構築した S3 上に格納する。その際、以下の修正を忘れないこと。
    • 36,38 行目の [Amazon S3 Bucket Name]
    • 45 行目の [Amazon Cognito Identity Pool の Identity Pool Id]
    • 48 行目の [Amazon Cognito User Pool の Pool Id]
    • 49 行目の [Amazon Cognito User Pool の App Client Id]
activation.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8" />
    <title>Activation & Forget Password</title>
    <!-- AWS SDK //-->
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.23.0.min.js"></script>
    <!-- Amazon Cognito //-->
    <script src="js/jsbn.js"></script>
    <script src="js/jsbn2.js"></script>
    <script src="js/sjcl.js"></script>
    <script src="js/aws-cognito-sdk.min.js"></script>
    <script src="js/amazon-cognito-identity.min.js"></script>
    <!-- jquery //-->
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <!-- bootstrap3 //-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <form class="form-activation">
            <h2 class="form-activation-heading">Activation</h2>
            <div id="message" class="alert" style="display:none;"></div>
            <label id="labelUsername">UserID</label><br>
            <input type="text" id="inputUsername" class="form-control" placeholder="UserID" required autofocus></input>
            <label id="labelActivationKey">Activation Key</label><br>
            <input type="activationkey" id="inputActivationKey" class="form-control" placeholder="Activation Key" required></input>
            <p></p>
            <input type="button" class="btn btn-lg btn-primary btn-bloc" id="activate_btn" value="Activate"></input>
            <input type="button" class="btn btn-lg btn-primary btn-bloc" id="send_key_btn" value="Re:Send Activation Key"></input>
            <input type="button" class="btn btn-lg btn-primary btn-bloc" id="forget_password_btn" value="Forget Password"></input>
            <p></p>
            <a href="http://[Amazon S3 Bucket Name].s3-website-ap-northeast-1.amazonaws.com/signin.html" target="_blank">SignIn</a>
            <p></p>
            <a href="http://[Amazon S3 Bucket Name].s3-website-ap-northeast-1.amazonaws.com/signup.html" target="_blank">SignUp</a>
        </form>
    </div>
    <script>
        // Initialize the Amazon Cognito credentials provider
        AWSCognito.config.region = "ap-northeast-1";
        AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId: "[Amazon Cognito Identity Pool の Identity Pool Id]"
        });
        var data = {
            UserPoolId: "[Amazon Cognito User Pool の Pool Id]",
            ClientId: "[Amazon Cognito User Pool の App Client Id]"
        };
        var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data);
        var attributeList = [];
        var cognitoUser;

        $("#activate_btn").click(function() {
            username = $("#inputUsername").val();
            activationkey = $("#inputActivationKey").val();
            if(!username) {
                $("#message").text("Input UserID !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            if(!activationkey) {
                $("#message").text("Input Activation Key !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            var userData = {
                Username : username,
                Pool : userPool
               };
            cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
            cognitoUser.confirmRegistration(activationkey, true, function(err, result){
                if (err) {
                    console.log(err);
                    message_text = err;
                    message_class = "alert-danger";
                    $("#message").text(message_text);
                    $("#message").addClass(message_class);
                    $("#message").show();
                } else {
                     var url = "signin.html";
                     $("form").fadeOut(100, function(){
                        $(location).attr("href", url);
                     });
                     $(".wrapper").addClass("form-success"); 
                }
            });
        });

        $("#send_key_btn").click(function() {
            username = $("#inputUsername").val();
            if(!username) {
                $("#message").text("Input UserName !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            var userData = {
                Username : username,
                Pool : userPool
               };
            cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
            cognitoUser.resendConfirmationCode(function(err, result) {
                if (err) {
                    console.log(err);
                    $("#message").text(err);
                    $("#message").addClass("alert-danger");
                    $("#message").show();
                } else {
                    $("#message").text("Send Activation Key.");
                    $("#message").addClass("alert-success");
                    $("#message").show();
                }
            });
        });

        $("#forget_password_btn").click(function() {
            username = $("#inputUsername").val();
            if(!username) {
                $("#message").text("Input UserID or Email !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            var userData = {
                Username : username,
                Pool : userPool
               };
            cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
            cognitoUser.forgotPassword({
                onSuccess: function (result) {
                    console.log("call result: " + result);
                },
                onFailure: function(err) {
                    alert(err);
                },
                inputVerificationCode() {
                    var verificationCode = prompt("Please input verification code ", "");
                    var newPassword = prompt("Enter new password ", "");
                    cognitoUser.confirmPassword(verificationCode, newPassword, this);
                }
            });
        });

    </script>
</body>
</html>

 
2. サイトへアクセスすると、以下の画面が表示されるので、適当な値を入力し、「Activate」ボタンを押下
 
スクリーンショット 2017-03-29 14.40.23.jpg
 
3. アクティベーションが完了する。

6.JavaScript からのサインインとユーザー情報の取得

  1. 以下の html ファイルを、「3.S3 に静的ウェブサイトを構築する。」で構築した S3 上に格納する。その際、以下の修正を忘れないこと。
    • 34,36 行目の [Amazon S3 Bucket Name]
    • 43,87 行目の [Amazon Cognito Identity Pool の Identity Pool Id]
    • 46,89 行目の [Amazon Cognito User Pool の Pool Id]
    • 47 行目の [Amazon Cognito User Pool の App Client Id]
signin.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8" />
    <title>Sign In</title>
    <!-- AWS SDK //-->
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.23.0.min.js"></script>
    <!-- Amazon Cognito //-->
    <script src="js/jsbn.js"></script>
    <script src="js/jsbn2.js"></script>
    <script src="js/sjcl.js"></script>
    <script src="js/aws-cognito-sdk.min.js"></script>
    <script src="js/amazon-cognito-identity.min.js"></script>
    <!-- jquery //-->
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <!-- bootstrap3 //-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <form class="form-signin">
            <h2 class="form-signup-heading">Sign In</h2>
            <div id="message" class="alert" style="display:none;"></div>
            <label id="labelUsername">UserID or Email</label><br>
            <input type="text" id="inputUsername" class="form-control" placeholder="UserID or Email" required autofocus></input>
            <label id="labelPassword">Password</label><br>
            <input type="password" id="inputPassword" class="form-control" placeholder="Password" required></input>
            <p></p>
            <input type="button" class="btn btn-lg btn-primary btn-bloc" id="sign_in_btn" value="Sign In"></input>
            <p></p>
            <a href="http://[Amazon S3 Bucket Name].s3-website-ap-northeast-1.amazonaws.com/signup.html" target="_blank">SignUp</a>
            <p></p>
            <a href="http://[Amazon S3 Bucket Name].s3-website-ap-northeast-1.amazonaws.com/activation.html" target="_blank">Activation & Forget Password</a>
        </form>
    </div>
    <script>
        // Initialize the Amazon Cognito credentials provider
        AWSCognito.config.region = "ap-northeast-1";
        AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId: "[Amazon Cognito Identity Pool の Identity Pool Id]"
        });
        var poolData = {
            UserPoolId: "[Amazon Cognito User Pool の Pool Id]",
            ClientId: "[Amazon Cognito User Pool の App Client Id]"
        };
        var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
        var attributeList = [];
        var cognitoUser;

        $("#sign_in_btn").click(function() {
            username = $("#inputUsername").val();
            password = $("#inputPassword").val();
            if(!username) {
                $("#message").text("Input UserID or Email !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            if(!password) {
                $("#message").text("Input Password !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            //event.preventDefault();
            var authenticationData = {
                Username : username,
                Password : password
            };
            var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
            var userData = {
                Username : username,
                Pool : userPool
                };
            cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
            console.log(cognitoUser);
            cognitoUser.authenticateUser(authenticationDetails, {
                onSuccess: function (result) {
                    console.log("Id      Token + " + result.getIdToken().getJwtToken());
                    console.log("Access  Token + " + result.getAccessToken().getJwtToken());
                    console.log("Refresh Token + " + result.refreshToken.token);
                    AWS.config.region = "ap-northeast-1";
                    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
                        IdentityPoolId: "[Amazon Cognito Identity Pool の Identity Pool Id]",
                        Logins: {
                            "cognito-idp.ap-northeast-1.amazonaws.com/[Amazon Cognito User Pool の Pool Id]" : result.getIdToken().getJwtToken()
                        }
                    });
                    AWS.config.credentials.get(function(err) {
                        if (!err) {
                            console.log("accessKeyId     + " + AWS.config.credentials.accessKeyId);
                            console.log("secretAccessKey + " + AWS.config.credentials.secretAccessKey);
                            console.log("sessionToken    + " + AWS.config.credentials.sessionToken);
                        }else{
                                log("Error : " + err);
                        }
                    });
                    var url = "mypage.html";
                    $("form").fadeOut(700, function(){
                        $(location).attr("href", url);
                    });
                    $(".wrapper").addClass("form-success"); 
                },
                onFailure: function(err) {
                    alert(err);
                },
                //mfaRequired: function(codeDeliveryDetails) {
                //    var verificationCode = prompt('Please input verification code' ,'');
                //    cognitoUser.sendMFACode(verificationCode, this);
                //}
            });
        });

    </script>
</body>
</html>

 
2. 以下の html ファイルを、「3.S3 に静的ウェブサイトを構築する。」で構築した S3 上に格納する。その際、以下の修正を忘れないこと。
* 54,197 行目の [Amazon Cognito Identity Pool の Identity Pool Id]
* 57,199 行目の [Amazon Cognito User Pool の Pool Id]
* 58 行目の [Amazon Cognito User Pool の App Client Id]

mypage.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8" />
    <title>My Page</title>
    <!-- AWS SDK //-->
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.23.0.min.js"></script>
    <!-- Amazon Cognito //-->
    <script src="js/jsbn.js"></script>
    <script src="js/jsbn2.js"></script>
    <script src="js/sjcl.js"></script>
    <script src="js/aws-cognito-sdk.min.js"></script>
    <script src="js/amazon-cognito.min.js"></script>
    <script src="js/amazon-cognito-identity.min.js"></script>
    <!-- jquery //-->
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <!-- IE //-->
    <script src="https://www.promisejs.org/polyfills/promise-7.0.4.min.js"></script>
    <!-- bootstrap3 //-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body onLoad="loadHello()" onUnload="unloadBye()">
    <div class="container">
        <form class="form-mypage" name="form1">
            <h2 class="form-mypage-heading">My Page</h2>
            <div id="message" class="alert" style="display:none;"></div>
            <label id="labelUsername">UserID : </label><br>
            <input type="hidden" id="inputUsername" class="form-control" placeholder="UserID" required autofocus></input>
            <label id="labelEmail">Email : </label><br>
            <input type="hidden" id="inputEmail" class="form-control" placeholder="Email" required autofocus></input>
            <input type="text" id="inputNewEmail" class="form-control" placeholder="New Email" required autofocus></input>
            <p></p>
            <input type="button" class="btn btn-lg btn-primary btn-bloc" id="update_btn" value="Update"></input>
            <p><br/></p>
            <label id="labelPassword">Old Password</label><br>
            <input type="password" id="inputPassword" class="form-control" placeholder="Old Password" required></input>
            <label id="labelNewPassword">New Password</label><br>
            <input type="password" id="inputNewPassword" class="form-control" placeholder="New Password" required></input>
            <label id="labelRetypeNewPassword">Retype New Password</label><br>
            <input type="password" id="inputRetypeNewPassword" class="form-control" placeholder="Retype New Password" required></input>
            <p></p>
            <input type="button" class="btn btn-lg btn-primary btn-bloc" id="change_password_btn" value="Change Password"></input>
            <p><br/></p>
            <input type="button" class="btn btn-lg btn-primary btn-bloc" id="sign_out_btn" value="Sign Out"></input>
        </form>
    </div>
    <script>
        // Amazon Cognito
        AWSCognito.config.region = "ap-northeast-1";
        AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId: "[Amazon Cognito Identity Pool の Identity Pool Id ]"
        });
        var data = {
            UserPoolId: "[Amazon Cognito User Pool の Pool Id]",
            ClientId: "[Amazon Cognito User Pool の App Client Id]"
        };
        var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data);
        var attributeList = [];
        var cognitoUser;

        $("#update_btn").click(function() {
            email = $("#inputEmail").val();
            newemail = $("#inputNewEmail").val();
            if(!newemail) {
                $("#message").text("Input New Email !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            var attributeList = [];
            var attribute = {
                Name : "email",
                Value : newemail
            };
            var attribute = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(attribute);
            attributeList.push(attribute);
            cognitoUser = userPool.getCurrentUser();
            console.log("cognitoUser : ");
            console.log(cognitoUser);
            if (cognitoUser != null) {
                cognitoUser.getSession(function(err, result) {
                    if (result) {
                        cognitoUser.updateAttributes(attributeList, function(err, result) {
                            if (err) {
                                console.log(err);
                                console.log(result);
                                $("#message").text(err);
                                $("#message").addClass("alert-danger");
                                $("#message").show();
                            } else {
                                $("#message").text("Update.");
                                $("#message").addClass("alert-success");
                                $("#message").show();
                            }
                        });
                    } else {
                        var url = "signin.html";
                        $(location).attr("href", url);
                    }
                });
            } else {
              var url = "signin.html";
              $(location).attr("href", url);
            }
        });

        $("#change_password_btn").click(function() {
            password = $("#inputPassword").val();
            newpassword = $("#inputNewPassword").val();
            retypenewpassword = $("#inputRetypeNewPassword").val();
            if(!password) {
                $("#message").text("Input Old Password !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            if(!newpassword) {
                $("#message").text("Input New Password !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            if(!retypenewpassword) {
                $("#message").text("Input Retype New Password !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            if(newpassword != retypenewpassword) {
                $("#message").text("Wrong Retype New Password !!");
                $("#message").addClass("alert-danger");
                $("#message").show();
                return false;
            }
            cognitoUser = userPool.getCurrentUser();
            console.log("cognitoUser : ");
            console.log(cognitoUser);
            if (cognitoUser != null) {
                cognitoUser.getSession(function(err, result) {
                    if (result) {
                        cognitoUser.changePassword(password, newpassword, function(err, result) {
                            if (err) {
                                console.log(err);
                                console.log(result);
                                $("#message").text(err);
                                $("#message").addClass("alert-danger");
                                $("#message").show();
                            } else {
                                $("#message").text("Change Password.");
                                $("#message").addClass("alert-success");
                                $("#message").show();
                            }
                        });
                    } else {
                        var url = "signin.html";
                        $(location).attr("href", url);
                    }
                });
            } else {
                var url = "signin.html";
                $(location).attr("href", url);
            }
        });

        $("#sign_out_btn").click(function() {
            cognitoUser = userPool.getCurrentUser();
            console.log("cognitoUser : ");
            console.log(cognitoUser);
            if (cognitoUser != null) {
                console.log(cognitoUser);
                cognitoUser.signOut();
            }
            var url = "signin.html";
            $(location).attr("href", url);
        });

        function loadHello() {
            console.log("userPool : ");
            console.log(userPool);
            cognitoUser = userPool.getCurrentUser();
            console.log("cognitoUser : ");
            console.log(cognitoUser);
            if (cognitoUser != null) {
                console.log("cognitoUser is not null.");
                cognitoUser.getSession(function(err, result) {
                    if (result) {
                        console.log("Id      Token + " + result.getIdToken().getJwtToken());
                        console.log("Access  Token + " + result.getAccessToken().getJwtToken());
                        console.log("Refresh Token + " + result.refreshToken.token);
                        console.log(result);
                        // Common
                        AWS.config.region = "ap-northeast-1";
                        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
                            IdentityPoolId: "[Amazon Cognito Identity Pool の Identity Pool Id ]",
                            Logins: {
                                "cognito-idp.ap-northeast-1.amazonaws.com/[Amazon Cognito User Pool の Pool Id]" : result.getIdToken().getJwtToken()
                            }
                        });
                        //
                        AWS.config.credentials.get(function(err) {
                            if (!err) {
                                console.log("accessKeyId     + " + AWS.config.credentials.accessKeyId);
                                console.log("secretAccessKey + " + AWS.config.credentials.secretAccessKey);
                                console.log("sessionToken    + " + AWS.config.credentials.sessionToken);
                            }else{
                                    log("Error : " + err);
                            }
                        });
                        cognitoUser.getUserAttributes(function(err, attrresult) {
                            if (err) {
                                alert(err);
                                return;
                            }
                            console.log(attrresult);
                            console.log(cognitoUser);
                            console.log(cognitoUser.username);
                            $("#labelUsername").html("UserID : " + cognitoUser.username);
                            document.getElementById("inputUsername").value = cognitoUser.username;
                            for (i = 0; i < attrresult.length; i++) {
                                if (attrresult[i].getName()=="email") {
                                    $("#labelEmail").html("Email : " + attrresult[i].getValue());
                                    document.getElementById("inputEmail").value = attrresult[i].getValue();
                                }
                            }
                            console.log(AWSCognito.config);
                            console.log(AWSCognito.config.credentials);
                            console.log("Cognito Identity Id: " + AWSCognito.config.credentials.identityId);
                        });
                    } else {
                        console.log("cognitoUser.getSession - Error.");
                        //var url = "signin.html";
                        //$(location).attr("href", url);
                    }
                });
            } else {
                console.log("cognitoUser is null.");
                //var url = "signin.html";
                //$(location).attr("href", url);
            }
        }

        function unloadBye() {
            console.log(AWS.config);
            //alert("Bye!");
        }

    </script>
</body>
</html>

 
3. サイトへアクセスすると、以下の画面が表示されるので、適当な値を入力し、「Sign In」ボタンを押下

スクリーンショット 2017-03-29 14.40.31.jpg
 
4. マイページが表示される。

スクリーンショット 2017-03-29 16.47.11.jpg

99.ハマりポイント

  • サインアップやアクティベートはすんなり行きましたが、サインインとユーザー情報の取得のところで躓きました。AWS.config.region = "ap-northeast-1"; この1行が無い所為で、全然認証が通らず。かなり困りました…。

XX.まとめ

色々なサイトを参考にさせてもらって、一通り確認することが出来ました。
本当は、参考元を記載しなければいけないところではあるんですが、
すいません、忘れてしまいました…。

次は、iOSから認証を確認しようかと思います。

48
50
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
48
50