LoginSignup
1
2

More than 3 years have passed since last update.

Cognito+API Gateway+LambdaでログインAPIを作りたいんだー!

Last updated at Posted at 2020-05-02

前回の続きで、Cognitoを使ったユーザ認証を行う。

やりたいこと

APIでログイン
- ログイン名 と パスワードをリクエストボディに指定しAPIをコールしアクセストークンを取得する

参考

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

やってみよう

Lambda用IAMロール

前回同様に、Lambdaの基本的なポリシーに加えて、「AmazonCognitoPowerUser」をアタッチする。

ログイン用のLambda関数を作成

前回と異なっていた点ですが、引数に渡すUSERNAME・PASSWORDは大文字で記載しないとエラーになりました。

index.js
'use strict';

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

/**
 * SignIn
 */
exports.handler = async (event, context) => {
  const response = {};
  let loginName;
  let password;
  console.log(event);

  // Validation
  if (!(event.body) || !('loginName' in JSON.parse(event.body)) || !('password' in JSON.parse(event.body))) {
    response["statusCode"] = 400;
    return response;

  } else {
    let reqestBody = JSON.parse(event.body);

    loginName = reqestBody["loginName"];
    password = reqestBody["password"];
  }

  // SignIn parameters
  const params = {
    AuthFlow: 'USER_PASSWORD_AUTH',
    ClientId: process.env['APP_CLIENT_ID'],
    AuthParameters: {
        USERNAME : loginName, 
        PASSWORD: password
    }
  };

  response["headers"] = {"Access-Control-Allow-Origin" : "*", "Content-Type" : "application/json"};

  // SignIn
  try {
      const result = await cognito.initiateAuth(params).promise();
      console.log('User sign in success!!!', JSON.stringify(result, null, 4));

      response["statusCode"] = 200;
      response["body"] = JSON.stringify(result['AuthenticationResult']);
      return response;
  }
  catch(err) {
      console.log('User sign in failed...' + err);

      if ((err.code == 'NotAuthorizedException') || (err.code == 'UserNotConfirmedException')) {
          response["statusCode"] = 400;
      } else {
          response["statusCode"] = 500;
      }

      return response;
  }
};

API Gateway リソース・メソッドの追加

前回同様、「Lambdaプロキシの統合」にチェックを入れ、作成したLambda関数を選択する。

API Gatewayからのテスト実行
image.png

無事にアクセストークンが取得できたので、目的達成!!!

感想

レスポンスの有効期限(expired)が3600なのでん?と思ったら、アクセストークン・IDトークンの有効期限は1時間固定のよう。
変更できないのか?? 調べておきます。
アプリクライアントの設定で指定したトークンの有効期限はリフレッシュトークンの有効期限のことである。

今後の宿題

  • ユーザ情報を取得する
1
2
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
1
2