LoginSignup
4
3

More than 5 years have passed since last update.

AWSのCognitoを使って画面サインインをやってみた

Last updated at Posted at 2019-04-12

前提

AWSでシステム構築を目指すセカンドステップです。

今回の掲載範囲はCogninito上に存在しているユーザープールへのユーザーのサインインを画面上から行うこと。
そのために必要なライブラリ取得、画面作成までを掲載します。

前回はAWSのCognitoを使って画面サインアップをやってみた

AWSには認証・認可を行ってくれるCognitoというサービスを用いてアプケーションにサインインを行いたいと思っています。
↓Cognitoのユーザー設定方法はこちら↓
(工事中)

基本的にAWSのチュートリアルを参考にしていますが、別途同じようなことをしている方々もいらしたので、かなり参考にさせて頂いています。
(先駆者の方々ありがとうございます!)

この記事が古くなっても新規のチュートリアルとの違いを確認しながら同じことが再現できることを目指します。

Cognitoのjavascript SDKのチュートリアル
https://docs.aws.amazon.com/ja_jp/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html

別途参考ページ
https://hawksnowlog.blogspot.com/2016/10/try-login-with-aws-https://dev.classmethod.jp/cloud/aws/login-form-by-using-aws-sdk-for-javascript/

利用したライブラリ一覧(前回と全く一緒)

Cognito SDK
https://raw.githubusercontent.com/aws/amazon-cognito-identity-js/master/dist/aws-cognito-sdk.min.js
https://raw.githubusercontent.com/aws/amazon-cognito-identity-js/master/dist/amazon-cognito-identity.min.js
http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn.js
http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn2.js
https://raw.githubusercontent.com/bitwiseshiftleft/sjcl/master/sjcl.js
http://momentjs.com/downloads/moment.js
AWSのSDK
https://github.com/aws/aws-sdk-js/releases/download/v2.6.6/browser.zip
JQuery
https://code.jquery.com/jquery-3.1.1.min.js

上記のライブラリをS3バケットに同一名で保存します。

なぜ、S3にライブラリを保存して使用したかというと、(httpで直接呼ばなかったか)
""""""""""""""""""""""""""""""""""""""""""""""""""
S3の機能であるWeb静的ホスティングを試してみたかった。

すべてhttpで貼り付けたら参照権限無いよってエラーがあり、
どのソースが原因か見つけるのが面倒だったため。
""""""""""""""""""""""""""""""""""""""""""""""""""
↓S3の設定方法はこちら↓
(工事中)

全ソースコード

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8" />
    <title>Cognitoサインイン</title>
 <!--上記で記載していたライブラリを読み込む(S3にアップした名前をsrc=""に入れる)//-->
    <!-- aws sdk //-->
    <!-- aws sdk //-->
    <script src="aws-sdk.min.js"></script>
    <!-- aws cognito sdk (public beta!!) //-->
    <script src="jsbn.js"></script>
    <script src="jsbn2.js"></script>
    <script src="sjcl.js"></script>
    <script src="moment.js"></script>
    <script src="aws-cognito-sdk.min.js"></script>
    <script src="amazon-cognito-identity.min.js"></script>
    <!-- jquery //-->
    <script src="jquery-3.1.1.min.js"></script>
 <!--上記で記載していたライブラリを読み込む(S3にアップした名前をsrc=""に入れる)//-->
    <!-- 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-signin-heading">サインイン</h2>
        <div id="message" class="alert" style="display:none;"></div>
        <label for="inputUsername" class="sr-only">ユーザー名</label>
        <input type="text" id="inputUsername" class="form-control" placeholder="User name" required autofocus></input>
        <label for="inputPassword" class="sr-only">パスワード</label>
        <input type="password" id="inputPassword" class="form-control" placeholder="Password" required></input>
        <br/>
        <input type="submit" class="btn btn-lg btn-primary btn-bloc" id="login-button" value="ログイン"></input>
    </form>
</div>
<script>
    <!--
    // 1 Amazon Cognito 認証情報プロバイダーを初期化します
    AWS.config.region = 'ap-northeast-1'; // リージョン(デフォルトだとこのまま)
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: 'ap-northeast-1:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',  // ID プールのID
    });
    //よくわからないけど初期化します
    AWSCognito.config.region = 'ap-northeast-1'; // リージョン(デフォルトだとこのまま)
    AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: 'ap-northeast-1:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',  // ID プールのID
    });
    //-->
</script>
<script>
    <!--
    $(function() {
        $("#login-button").click(function(event){
            //画面上の入力値であるメールアドレス+パスワードを代入する
            event.preventDefault();
            var authenticationData = {
                Username : $('#inputUsername').val(),
                Password : $('#inputPassword').val(),
            };
            var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);

            // 2 Amazon Cognito Userpoolの指定+クライアントアプリの指定
            var poolData = {
                UserPoolId: 'ap-northeast-1_xxxxxxxxx', //ユーザープール用のID
                ClientId: 'zzzzzzzzzzzzzzzzzzzzzzzzzz' //サインイン用アプリID フェデレーションIDのCognito認証に利用したクライアントアプリのID
            };

            var userPool = new  AmazonCognitoIdentity.CognitoUserPool(poolData);
            var userData = {
                Username : $("#inputUsername").val(),
                Pool : userPool
            };

            var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
            cognitoUser.authenticateUser(authenticationDetails, {
                onSuccess: function (authresult) {
                    alert("Well done!");
                },
                onFailure: function(err) {
                    alert(err.message);
                    alert("You are looser");
                },
            });
        });
    });
    //-->
</script>
</body>
</html>

 1 AWS認証情報の取得のための最新コードはCognitoのサンプルコードにあり(今回のプラットフォームはjavascriptで記述)

IdentitypoolID.png

2 チュートリアルのユーザ認証(チュートリアルのClientIdが何か分からなくなりやすい)

CognitoAuthentication.png

フェデレーションIDのCognito認証に利用したクライアントアプリのIDの設定することに注意

cognitofedelation.png

感想

signin.png
サインイン出来ました!
well done!の部分に遷移後のリンクを記述することで遷移画面に跳ぶことができます。
(今回はCognitoの認証確認が目的なのでやりませんでした。)

注意

原因は調べていませんが、

var poolData = {
                UserPoolId: 'ap-northeast-1_xxxxxxxxx', //ユーザープール用のID
                ClientId: 'zzzzzzzzzzzzzzzzzzzzzzzzzz' //サインイン用アプリID フェデレーションIDのCognito認証に利用したクライアントアプリのID
            };
            var userPool = new  AmazonCognitoIdentity.CognitoUserPool(poolData);

をfunction()の外側に持っていったら動かなくなった。。なぜ。。(なので、やらないで)

4
3
1

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
4
3