如何在建立 Amazon Cognito 使用者集區後變更屬性?

3 分的閱讀內容
0

我建立了一個 Amazon Cognito 使用者集區,現在我想變更註冊使用者必要的標準屬性。

簡短描述

您無法在建立使用者集區之後變更標準使用者集區屬性。相反地,請使用在註冊使用者時,您想要求的屬性來建立新的使用者集區。然後,使用 AWS Lambda 函數作為遷移使用者觸發程序,將現有使用者遷移到新的使用者集區

**注意:**您可以將自訂屬性新增至現有的使用者集區,但註冊使用者不需要這些屬性。

解決方法

設定具有不同屬性的新使用者集區

建立新的使用者集區。然後,在選擇建立集區之前,根據您的偏好編輯標準屬性

重要:如果您在使用者集區中指定新的必要屬性,則請設計 Lambda 函數將這些新屬性提供給新使用者集區。如果您未設計此函數來提供新屬性,則會在使用者遷移期間驗證失敗。例如,假設您的舊使用者集區只要求電子郵件,但現在您的新使用者集區要求電子郵件電話號碼。在此情況下,請將電話號碼的屬性值傳遞至新的使用者集區,才能成功驗證使用者。

建立 Lambda 函數

若要建立使用者遷移 Lambda 函數,使用 Lambda 主控台編輯器建立和上傳您自己的部署套件

**重要:**此範例程式碼無法遷移在舊使用者集區中使用多重要素驗證 (MFA) 的使用者。

若要測試您的組態,請在 Python 中使用下列範例:

# Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import json
import boto3

client = boto3.client('cognito-idp')

def lambda_handler(event, context):
   if (event['triggerSource'] == 'UserMigration_Authentication'):
     user = client.admin_initiate_auth(
       UserPoolId='<user pool id of the user pool where the user already exists>',
       ClientId='<app client id of the user pool where the user already exists>',
       AuthFlow='ADMIN_NO_SRP_AUTH',
       AuthParameters={
         'USERNAME': event['userName'],
         'PASSWORD': event['request']['password']
       }
     )
        if (user):
       userAttributes = client.get_user(
         AccessToken=user['AuthenticationResult']['AccessToken']
       )
       for userAttribute in userAttributes['UserAttributes']:
         if userAttribute['Name'] == 'email':
           userEmail = userAttribute['Value']
           #print(userEmail)
           event['response']['userAttributes'] = {
             "email": userEmail,
             "email_verified": "true"
           }
          event['response']['messageAction'] = "SUPPRESS"
       print (event)
       return (event)
     else:
       return('Bad Password')
   elif (event["triggerSource"] == "UserMigration_ForgotPassword"):
     user = client.admin_get_user(
       UserPoolId='<user pool id of the user pool where the already user exists>',
       Username=event['userName']
     )
     if (user):
       for userAttribute in user['UserAttributes']:
         if userAttribute['Name'] == 'email':
           userEmail = userAttribute['Value']
           print(userEmail)
           event['response']['userAttributes'] = {
             "email": userEmail,
             "email_verified": "true"
           }
       event['response']['messageAction'] = "SUPPRESS"
          print (event)
       return (event)
     else:
       return('Bad Password')
          else:
     return('there was an error')

注意:UserPoolId 取代為舊使用者集區的 ID。請在 Amazon Cognito 主控台中,使用者集區管理頁面上的一般設定索引標籤中尋找此 ID。將 ClientId 取代為舊使用者集區的應用程式用戶端 ID。請在 Amazon Cognito 主控台中,尋找應用程式用戶端下方的應用程式用戶端 ID。

將遷移使用者觸發程序新增至新使用者集區

Amazon Cognito 主控台中,將您的新 Lambda 函數設定為遷移使用者 Lambda 觸發程序。如需詳細資訊,請參閱新增使用者集區 Lambda 觸發程序

為遷移使用者開啟 USER_PASSWORD_AUTH 流程

設定您的使用者集區應用程式用戶端,在遷移時使用 USER_PASSWORD_AUTH 驗證流程。此驗證流程可讓您的應用程式將使用者的使用者名稱和密碼傳遞至 Lambda 函數。然後,驗證流程可以從現有使用者集區驗證使用者。

請將邏輯新增到您的應用程式,以將預設驗證流程變更為USER_PASSWORD_AUTH 流程。讓邏輯變更登入嘗試的驗證流程,其中使用者存在於舊使用者集區,而非新使用者集區。

例如,如果您的應用程式使用 JavaScript,請將 cognitoUser.setAuthenticationFlowType 指定為 USER_PASSWORD_AUTH

**注意:**遷移使用者後,最佳實務是將應用程式的驗證流程變更為 USER_SRP_AUTH。此流程會使用安全遠端密碼 (SRP) 通訊協定驗證使用者,無需透過網路傳送密碼。與 USER_PASSWORD_AUTH 流程相比,此流程也具有安全性的優點。

cognitoUser.setAuthenticationFlowType('USER_PASSWORD_AUTH');
    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function(result) {
            // User authentication was successful
        },
        onFailure: function(err) {
            // User authentication was not successful
        },
        mfaRequired: function (codeDeliveryDetails) {
            // MFA is required to complete user authentication.
            // Get the code from user and call
            cognitoUser.sendMFACode(verificationCode, this);
        }
    });

測試設定

使用 Amazon Cognito 託管 Web UI 登入您的應用程式,以測試驗證流程。您登入的使用者,會使用新的使用者集區進行驗證,然後進行遷移。

**注意:**如果您沒有可用於登入測試組態的使用者帳戶,請建立新使用者

疑難排解問題

如果您在測試時收到錯誤訊息,例如「遷移使用者期間發生例外狀況」,請從 Lambda 開啟記錄陳述式。此設定會將遷移使用者 Lambda 觸發程序的參數記錄至 Amazon CloudWatch 日誌。請重現該錯誤,然後檢閱日誌,查看在遷移使用者 Lambda 觸發程序中是否有任何參數或語法錯誤的問題。

相關資訊

使用 Lambda 觸發程序自訂使用者集區工作流程

Amazon Cognito 使用者集區和身分池之間有什麼區別?

使用者集區

AWS 官方
AWS 官方已更新 9 個月前