跳至內容

我該如何使用 AWS CLI 在 Amazon Cognito 中重設使用者的密碼?

2 分的閱讀內容
0

我想使用 AWS Command Line Interface (AWS CLI) 協助使用者在 Amazon Cognito 中重設或變更其密碼。

解決方法

**注意:**如果您在執行 AWS CLI 命令時收到錯誤,請參閱對 AWS CLI 錯誤進行疑難排解。此外,請確定您使用的是最新的 AWS CLI 版本。在以下命令中,請將 VALID-ACCESS-TOKENUSER-POOL-IDCLIENT-IDUSERNAMECONFIRMATION-CODENEW-PASSWORD 以及 PREVIOUS-PASSWORD 替換為您的實際值。

以使用者身分變更密碼

**注意:**若要執行 change-password 命令,使用者必須具備已登入使用者的存取權杖。該存取權杖必須包含 aws.cognito.signin.user.admin 範圍。

若要以使用者身分變更密碼,請執行以下 change-password 命令:

aws cognito-idp change-password --previous-password PREVIOUS-PASSWORD --proposed-password NEW-PASSWORD --access-token VALID-ACCESS-TOKEN

以系統管理員身分重設使用者密碼

系統管理員要重設使用者密碼時,使用者必須在使用者集區中具有已驗證的電子郵件或電話號碼。當系統管理員執行 admin-reset-user-password 命令時,Amazon Cognito 會自動將驗證碼傳送至使用者已驗證的聯絡方式。

請以系統管理員身分執行以下 admin-reset-user-password 命令以重設使用者密碼:

aws cognito-idp admin-reset-user-password --user-pool-id USER-POOL-ID --username USERNAME

**注意:**當系統管理員重設密碼後,使用者嘗試登入時,會收到「PasswordResetRequiredException」錯誤訊息。接著,Amazon Cognito 會將使用者重新導向至忘記密碼流程。

在系統管理員執行 admin-reset-user-password 命令後,使用者需執行以下 confirm-forgot-password 命令以設定新密碼:

aws cognito-idp confirm-forgot-password --client-id CLIENT-ID --username USERNAME --confirmation-code CONFIRMATION-CODE --password NEW-PASSWORD

如果使用者沒有已驗證的電子郵件地址或電話號碼,系統管理員會收到「An error occurred (InvalidParameterException) when calling the AdminResetUserPassword operation: Cannot reset password for the user as there is no registered/verified email or phone_number」錯誤訊息。

若要解決此問題,系統管理員需執行以下 admin-update-user-attributes 命令,以驗證使用者的聯絡資訊,並將 email_verifiedphone_number_verified 屬性設為 true

aws cognito-idp admin-update-user-attributes --user-pool-id USER-POOL-ID --username USERNAME --user-attributes Name="email_verified",Value="true"

在系統管理員完成使用者聯絡資訊驗證後,即可再次執行 admin-reset-user-password 命令。在使用者收到驗證碼後,使用者即可執行 confirm-forgot-password 命令以設定新密碼。

如果使用者仍未收到驗證碼,請參閱 為什麼 Amazon Cognito 未使用 ForgotPassword API 呼叫傳送驗證碼電子郵件或簡訊?

以系統管理員身分設定永久或臨時密碼

若要為使用者設定永久密碼,系統管理員請執行以下 admin-set-user-password 命令:

aws cognito-idp admin-set-user-password --user-pool-id USER-POOL-ID --username USERNAME --password NEW-PASSWORD --permanent

接著,使用者即可使用新的永久密碼登入。

若要為使用者設定臨時密碼,系統管理員請執行以下 admin-set-user-password 命令:

aws cognito-idp admin-set-user-password --user-pool-id USER-POOL-ID --username USERNAME --password TEMPORARY-NEW-PASSWORD --no-permanent

在系統管理員設定臨時密碼後,使用者的狀態會變更為 FORCE_CHANGE_PASSWORD。在使用者使用臨時密碼登入後,會收到 NEW_PASSWORD_REQUIRED 挑戰。

**注意:**用於完成密碼挑戰的工作階段權杖有效時間為 3 分鐘。您可以在應用程式用戶端的驗證流程持續時間設定中修改此持續時間

接著,使用者需執行以下 respond-to-auth-challenge 命令以設定新密碼:

aws cognito-idp respond-to-auth-challenge --client-id CLIENT-ID --challenge-name NEW_PASSWORD_REQUIRED --challenge-responses USERNAME=example_username,NEW_PASSWORD="example_new_password" --session "example_session_token"

**重要:**如果您為應用程式用戶端設定了用戶端祕密,則使用者在存取使用者集區時,必須在 respond-to-auth-challenge 命令中包含秘密雜湊參數。如果使用者收到「Unable to verify secret hash for client」錯誤,請參閱對從 Amazon Cognito 使用者集區 API 傳回的「Unable to verify secret hash for client」錯誤,該如何進行疑難排解?

AWS 官方已更新 9 個月前