跳至內容

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

3 分的閱讀內容
0

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

簡短描述

您無法在建立使用者集區之後變更標準使用者集區屬性。請改為建立一個新的使用者集區,並設定您想要在使用者註冊時要求的屬性。然後,使用 AWS Lambda 函式作為遷移使用者觸發程序,將現有使用者遷移到新的使用者集區

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

解決方法

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

建立新的使用者集區。接著,在您選擇 Create pool (建立集區) 之前,請依照您的偏好編輯標準屬性

重要:如果您在使用者集區中指定新的必要屬性,請設計您的 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 主控台中,於使用者集區的管理頁面上,在 General settings (一般設定) 索引標籤中找到該 ID。將 ClientId 替換為舊使用者集區的應用程式用戶端 ID。在 Amazon Cognito 主控台的 App clients (應用程式用戶端) 下找到應用程式用戶端 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 登入您的應用程式,以測試驗證流程。您用來登入的使用者會先使用新的使用者集區完成驗證,接著進行遷移。

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

疑難排解問題

如果您在測試時收到錯誤訊息 (例如「Exception during user migration」),請在 Lambda 中開啟記錄陳述式。此設定會將使用者遷移 Lambda 觸發程序的參數記錄到 Amazon CloudWatch 日誌。請重現錯誤,然後檢閱日誌,確認使用者遷移 Lambda 觸發程序的參數是否有問題,或是否有語法錯誤。

相關資訊

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

Amazon Cognito 使用者集區與身分池有何差異?

使用者集區

AWS 官方已更新 2 年前