2017-02-15 105 views
0

我試圖使用在AWS中的Node.js中編寫的Lambda函數來驗證用戶。我現在卡住了。 預期下面的代碼不起作用:如何使用Lambda函數和AWS Cognito認證用戶?

var AWS = require('aws-sdk'); 
 
exports.handler = (event, context, callback) => { 
 
    AWS.config.region = 'us-east-1'; 
 
     var authenticationData = { 
 
     Username : 'username', 
 
     Password : 'password', 
 
    }; 
 
    var authenticationDetails = new AWS.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData); 
 
    var poolData = { UserPoolId : 'My-Pool-Id', 
 
     ClientId : 'My-Client-Id' 
 
    }; 
 
    var userPool = new AWS.CognitoIdentityServiceProvider.CognitoUserPool(poolData); 
 
    var userData = { 
 
     Username : 'username', 
 
     Pool : userPool 
 
    }; 
 
    var cognitoUser = new AWS.CognitoIdentityServiceProvider.CognitoUser(userData); 
 
    cognitoUser.authenticateUser(authenticationDetails, { 
 
     onSuccess: function (result) { 
 
      console.log('access token + ' + result.getAccessToken().getJwtToken()); 
 
      
 
      console.log('idToken + ' + result.idToken.jwtToken); 
 
     }, 
 

 
     onFailure: function(err) { 
 
      alert(err); 
 
     }, 
 

 
    }); 
 

 
};

以上是Cognito Documentation page

提供的代碼,但我得到的是以下錯誤:

TypeError: AWS.CognitoIdentityServiceProvider.AuthenticationDetails is not a function 

有人對我現在應該做什麼有一些想法嗎? 謝謝

回答

1

您正在使用AWSCognito但未定義。將其更改爲AWS

您是否正在爲cognito編寫包裝?您可以在客戶端而不是在Lambda中執行此身份驗證。

+0

嗨@doorstuck,我已經更改爲AWS,但我得到了同樣的錯誤。至於包裝,我不確定,我是一個新手。我所做的只是在第一行代碼中聲明這個「var AWS = require('aws-sdk');」。我剛剛編碼內聯,並沒有上傳任何文件。我應該上傳任何圖書館嗎? – blackjack

+1

@blackjack我試圖弄清楚爲什麼你在後端編寫這個登錄代碼,而不是在客戶端。通常情況下,我會將您擁有的代碼寫入客戶端,然後使用從其獲取的憑據來調用其他AWS資源。您甚至可以使用您在客戶端獲得的憑據來調用API網關並驗證請求。這是構建到API網關。 您可以更新您的代碼示例並更改爲AWS.CognitoIdentityServiceProvider.AuthenticationDetails。 – doorstuck

+0

我很害怕我走錯了路。我正嘗試構建一個使用lambda的無服務器體系結構來管理所有用戶身份驗證和註冊流程(登錄,重置密碼,確認以及其他)。我會更改代碼並給客戶一些責任。我將嘗試瞭解AWS API Gateway如何驗證客戶端憑據。 – blackjack

相關問題