AWS Cognito密码重置功能失效,请求代码排查与修正
Hey there! Let's figure out why your AWS Cognito password reset flow isn't working. I've gone through your code snippets and spotted several key issues to fix:
Key Issues & Fixes
1. AJAX Request Problems
Your original GET request sends a stringified email ID in the request body, which is not standard for GET requests (most servers ignore request bodies for GET). Plus, you weren't handling AJAX errors, so if this backend call failed, you'd never know.
Fix:
- Switch to a POST request (more appropriate for sending data to a backend)
- Wrap the email ID in an object for easier backend parsing
- Add an error callback to catch backend request failures
- Avoid
async: false(it blocks the browser; your logic is already in the success callback so async is safe)
2. Asynchronous Confirmation Handling
You were showing the "success" message immediately after calling confirmPassword, but this is an asynchronous operation. The success message would pop up even if the password confirmation failed.
Fix:
- Move the success/error logic into
confirmPassword's ownonSuccessandonFailurecallbacks - Add a small delay before redirecting so the user can see the success message
3. Error Message Clarity
Your original code displayed the raw error object directly, which would show something like [object Error] instead of a human-readable message.
Fix:
- Use
err.messageto display the actual error text
Modified Code Snippet
var EmailId = document.getElementById('email').value; $.ajax({ url: EndPointURL + '/userapproval', type: 'POST', // Switch to POST for sending data data: JSON.stringify({ EmailId: EmailId }), // Wrap email in an object contentType: 'application/json; charset=utf-8', async: true, // Remove blocking synchronous behavior success: function (response) { // Avoid redundant JSON parsing if jQuery already parsed the response var data = typeof response === 'object' ? response : JSON.parse(response); var len = data.length; for (var i = 0; i < len; i++) { if (EmailId === data[i].EmailId) { var status = data[i].status; if (status.toLowerCase() !== "rejected") { // Initialize Cognito resources var poolData = { UserPoolId: poolId, ClientId: clientId }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); var userData = { Username: EmailId, Pool: userPool }; var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData); // Updated password reset flow cognitoUser.forgotPassword({ onSuccess: function (result) { console.log('Password reset initiated:', result); }, onFailure: function (err) { $("#lbl_alert").html(err.message || 'An unknown error occurred'); $("#myAlertModal").modal('show'); }, inputVerificationCode: function (data) { console.log('Verification code sent to:', data); var verificationCode = prompt('Please input verification code ', ''); if (!verificationCode) return false; var newPassword = prompt('Enter new password ', ''); if (!newPassword) return false; // Handle password confirmation asynchronously cognitoUser.confirmPassword(verificationCode, newPassword, { onSuccess: function () { $("#lbl_alert").html("Password reset successfully."); $("#myAlertModal").modal('show'); // Add delay so user sees the success message before redirect setTimeout(() => { document.location = 'Login.html'; }, 1500); }, onFailure: function (err) { $("#lbl_alert").html(err.message || 'Failed to confirm password'); $("#myAlertModal").modal('show'); } }); } }); } } } }, error: function(xhr, status, err) { // Catch AJAX request failures $("#lbl_alert").html('Failed to verify user status: ' + err); $("#myAlertModal").modal('show'); } });
Additional Checks to Ensure Success
- Verify Cognito Client Settings: In the AWS Cognito Console, make sure your app client has "Enable password reset" turned on (under App client settings).
- User Status: Ensure the user is in an
ENABLEDstate (Cognito won't allow password resets for unconfirmed or disabled users). - SDK Loading: Confirm you've loaded the AWS Cognito SDK correctly (
amazon-cognito-identity.min.js) and that all dependencies are present. - Email Verification: If your user pool requires email verification, make sure the user's email is verified (Cognito won't send reset codes to unverified emails).
内容的提问来源于stack exchange,提问作者Vipul Tripund

