LoginSignup
5
8

More than 3 years have passed since last update.

LambdaでCognito認証(ユーザー認証)

Last updated at Posted at 2020-01-10

はじめに

SDKをローカルに持ってきてゴニョるサンプルは検索に引っかかるのですが、
クラウド側(Lambda関数内部)で完結するサンプルが見つからない...
よし、ならば投稿してしまえ。

トップ
ユーザー作成
ユーザー確認
ユーザー認証 ←イマココ
ユーザー認可

ユーザー認証 (InitiateAuth)

通知されたIDとパスワードの組み合わせが正しいかを検証します。
登録された情報と一致した場合、ユーザー認証に必要なIDトークンを発行します。

ドキュメント

ソースコード

'use strict';

const AWS = require('aws-sdk');
const cognito = new AWS.CognitoIdentityServiceProvider();

/**
 * initiateAuthする
 * @param {string} userId ユーザーのメールアドレスor電話番号
 * @param {string} userPassword ユーザーのパスワード
 * @returns {Promise<Object>} HTTPレスポンス 200 OK
 */
module.exports = async (userId, userPassword) => {

  // ConfirmSignUpのパラメーター
  const params = {
    AuthFlow: 'USER_PASSWORD_AUTH', // ユーザープールの 全般設定>アプリクライアント>認証フローの設定 で指定した認証方法
    ClientId: '{アプリクライアントID}', // ユーザープールの 全般設定>アプリクライアント で確認する
    AuthParameters: {
      'USERNAME': userId,
      'PASSWORD': userPassword,
    },
  };

  // initiateAuth実行
  const result = await cognito.initiateAuth(params).promise().catch(error => {
    // 必要に応じて例外処理を追加する。
    // 例えば、パスワード不一致の例外は→「error.code == 'NotAuthorizedException'」
    throw error;
  });

  // HTTPレスポンス 必要に応じて編集する。
  // 例えば、IDトークンをcookieに設定したい場合は、headersに↓これを追加する。
  // 'Set-Cookie': `IdToken=${result.AuthenticationResult.IdToken}; Max-Age=${result.AuthenticationResult.ExpiresIn}`
  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
    },
    body: JSON.stringify({
      IdToken: result.AuthenticationResult.IdToken,
    }),
  };
};
5
8
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
5
8