LoginSignup
22
26

More than 5 years have passed since last update.

AWS cognito使ってnode.jsで認証だけしてみる

Last updated at Posted at 2017-10-19

2017/10/20のAWS-SDKのバージョンで動くもの。とりあえずテスト用に最短で。
テスト時にいちいちSignUpフォームやConfirmフォーム作るとかダルいので、とりあえずConfirmを認証時に一緒に行うようにしてみました。

1.npmでSDKをインストール

npm install aws-sdk --save
npm install amazon-cognito-identity-js --save

2.AWS cognitoでユーザー作成

AWS Cognitoのメニューから適当なユーザープールとアプリクライアント作成します。

ユーザープール ※チェックを全部外しておくと楽

image.png

アプリクライアント ※クライアントシークレットはいらない

image.png

ただしちょっと問題というか、ステータスのところがFORCE_CHANGE_PASSWORDとなっていて、ユーザー登録が完了していない状態です(Confirmが必要)
image.png

これはメールを送ってもConfirm画面に遷移できるわけでもなく、自分でConfirm画面を用意せねばなりません。テストしたいだけなので、ここを飛ばす(仮パスワードでそのままConfirmを行う)ようにプログラムします。

3.パスワードComplete付き認証プログラム

auth.js
var aws_cognito = require('amazon-cognito-identity-js');

// ユーザープール設定
var user_pool = new aws_cognito.CognitoUserPool({
    UserPoolId : 'AWS Cognitoで作ったユーザープールのプールID',
    ClientId : 'AWS Cognitoで作ったアプリクライアントID'
});

// ユーザー決定
const cognito_user = new aws_cognito.CognitoUser({
    Username: 'ユーザー名',
    Pool: user_pool,
});

// パスワードの設定
const authentication_details = new aws_cognito.AuthenticationDetails({
    Password: 'パスワード',
});

// ユーザープール/ユーザー/パスワードを使って認証
cognito_user.authenticateUser(authentication_details, {
    // 成功時
    onSuccess(result){
        // 認証完了トークンを取得。以降はこのトークンで認証済み確認
        console.log(result.getAccessToken().getJwtToken());
    },
    onFailure(err){
        console.error(err);
    },

    // ####################################################################################
    // 初回認証時はパスワードの変更が要求されるので、仮パスワードと同じパスワードを再設定する
    newPasswordRequired(user_attributes, required_attributes){
        cognito_user.completeNewPasswordChallenge(authentication_details.password, user_attributes, this);
    },
    // ####################################################################################
});

設定する時はUsername/Passwordですが、拾う時はusername/passwordと小文字になるところがちょとイヤラシイですね(´・ω・`)

おまけ

アクセストークン検証

・ライブラリを入れる

npm install jsonwebtoken --save

・ライブラリを読み込む

var jwt = require('jsonwebtoken');

・トークンを分解

var decoded = jwt.decode(access_token, {complete: true});
console.log(decoded);

検証方法はAWSのマニュアル辺りを参考に

トークン更新

・RefreshToken保存(有効期限30日)

// RefreshToken文字列を取得
refresh_token_str = result.getRefreshToken().getToken();

・Token更新

// RefreshToken文字列からRefreshTokenオブジェクトへ
refresh_token = new aws_cognito.CognitoRefreshToken({RefreshToken: "保存しておいたRefreshToken文字列"});

// 更新
cognito_user.refreshSession(refresh_token, (err, result)=>{
    // 新しいAccessTokenが取得できる
    var access_token = result.getAccessToken().getJwtToken();

    // RefreshTokenの更新とかも
    ...
});
22
26
2

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
22
26