身分驗證後 Lambda 觸發程序 - Amazon Cognito

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

身分驗證後 Lambda 觸發程序

由於 Amazon Cognito 會在登入使用者之後叫用此觸發程序,因此您可以在 Amazon Cognito 驗證使用者後新增自訂邏輯。

身分驗證流程概觀

身分驗證後 Lambda 觸發程序 – 用戶端流程

如需更多詳細資訊,請參閱 使用者集區身分驗證流程

身分驗證後 Lambda 觸發程序參數

Amazon Cognito 傳遞至此 Lambda 函數的請求,是以下參數和 Amazon Cognito 新增至所有請求的常用參數之組合。

JSON
{ "request": { "userAttributes": { "string": "string", . . . }, "newDeviceUsed": boolean, "clientMetadata": { "string": "string", . . . } }, "response": {} }

身分驗證後請求參數

newDeviceUsed

此旗標指出使用者是否已在新的裝置登入。唯有當使用者集區的記住裝置值為 AlwaysUser Opt-In 時,Amazon Cognito 才會設定此旗標。

userAttributes

代表使用者屬性的一或多組名稱/值。

clientMetadata

您可以做為 Lambda 函數的自訂輸入提供的一個或多個鍵值組,該函數是您用於身分驗證後觸發程序所指定。若要將此資料傳遞至您的 Lambda 函數,您可以使用 AdminRespondToAuthChallengeRespondToAuthChallenge API 動作中的 ClientMetadata 參數。Amazon Cognito 不包含其傳遞至身分驗證後函數的請求中的 AdminInitiateAuthInitiateAuth API 操作的 ClientMetadata 參數中的資料。

身分驗證後回應參數

Amazon Cognito 不預期會在回應中收到任何其他傳回的資訊。您的函數可使用 API 操作來查詢和修改您的資源,或將事件中繼資料記錄到外部系統。

身分驗證教學課程

Amazon Cognito 登入使用者之後,會立即啟用身分驗證後 Lambda 函數。請參閱 JavaScript、Android 和 iOS 適用的登入教學課程。

平台 教學課程
JavaScript 身分 SDK 使用 JavaScript 登入使用者
Android 身分 SDK 使用 Android 登入使用者
iOS 身分 SDK 使用 iOS 登入使用者

身分驗證後範例

這個身分驗證後範本 Lambda 函數,會將成功登入的資料傳送到 CloudWatch Logs。

Node.js
const handler = async (event) => { // Send post authentication data to Amazon CloudWatch logs console.log("Authentication successful"); console.log("Trigger function =", event.triggerSource); console.log("User pool = ", event.userPoolId); console.log("App client ID = ", event.callerContext.clientId); console.log("User ID = ", event.userName); return event; }; export { handler }
Python
import os def lambda_handler(event, context): # Send post authentication data to Cloudwatch logs print ("Authentication successful") print ("Trigger function =", event['triggerSource']) print ("User pool = ", event['userPoolId']) print ("App client ID = ", event['callerContext']['clientId']) print ("User ID = ", event['userName']) # Return to Amazon Cognito return event

Amazon Cognito 會將事件資訊傳遞至您的 Lambda 函數。此函數會將相同事件物件傳回 Amazon Cognito,並在回應中附上任何變更。在 Lambda 主控台中,您可使用與 Lambda 觸發程序相關聯的資料來設定測試事件。下列是此程式碼範例的測試事件:

JSON
{ "triggerSource": "testTrigger", "userPoolId": "testPool", "userName": "testName", "callerContext": { "clientId": "12345" }, "response": {} }