環境
・Node.js 6.10
・AWS Lambda
現状
Node.jsを用いて, AWS Cognitoにおけるログイン認証を実現しようとしています。
'use strict'; const AWS = require("aws-sdk"); global.fetch = require("node-fetch"); const AmazonCognitoIdentity = require("amazon-cognito-identity-js"); const CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool; const common = require("./common"); exports.handler = (event, context, callback) => { const response = common.response(); initilize(event, context) .then((data) => { return cognito_login(data); }) .then((data) => { response.body = JSON.stringify(data); callback(null, response); return; }) .catch((e) => { response.body = JSON.stringify(e); callback(null, response); return; }); }; // Initialize variables const initilize = (event, context) => { return new Promise((resolve, reject) => { if (!JSON.parse(event.body) || !event.body) reject(); else if (!JSON.parse(event.body).address) reject(); else if (!JSON.parse(event.body).password) reject(); else resolve(JSON.parse(event.body)); }); }; // Login user const cognito_login = (data) => { return new Promise((resolve, reject) => { const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails({ Username: data.address, Password: data.password }); const userPool = new AmazonCognitoIdentity.CognitoUserPool({ UserPoolId: common.get_cognito().userPoolId, ClientId: common.get_cognito().clientId }); const cognitoUser = new AmazonCognitoIdentity.CognitoUser({ Username: data.address, Pool: userPool }); cognitoUser.authenticateUser(authenticationDetails, { onSuccess: function(result) { AWS.config.region = common.get_cognito().region; AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: common.get_cognito().identityPoolId, Logins: { "cognito-idp.[region].amazonaws.com/[region]_[userpoolid]": result.getIdToken().getJwtToken() } }); AWS.config.credentials.refresh((err) => { (err)? reject(err): resolve("Successfully login."); }); }, onFailure: function(err) { console.log(err); reject(err); } }); }); };
上記のプログラムを実行すると、以下のようなエラーが発生します。
{ "code": "UnknownError", "message": "Unknown error, the response body from fetch is: undefined" }
あなたの回答
tips
プレビュー