使用原生JavaScript调用Cognito时出现NotAuthorizedException异常
Cognito登录提示"用户名或密码错误"但凭证无误
环境与配置
- 使用NPM包中的
amazon-cognito-identity.min.js,HTML引入代码:<script src="cognito-identity-js/amazon-cognito-identity.min.js"></script> - 已创建Cognito用户池,通过自定义UI实现注册、登录页面
- 用户完成注册流程,邮箱已接收验证码并完成验证
- 登录时持续触发错误:
NotAuthorizedException: Incorrect username or password.
- 已多次确认邮箱、密码无拼写错误
登录实现代码
function getCognitoUserPool() { const userPoolId = 'xxxx'; // 替换为你的用户池ID const clientId = 'xxxxx'; // 替换为你的应用客户端ID return new AmazonCognitoIdentity.CognitoUserPool({ UserPoolId: userPoolId, ClientId: clientId, }); } // 用户登录Cognito函数 async function signInUser(email, password) { try { const authenticationData = { Username: email, Password: password, }; const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData); const userPool = getCognitoUserPool(); const userData = { Username: email, Pool: userPool }; console.log(email, password) const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData); return new Promise((resolve, reject) => { cognitoUser.authenticateUser(authenticationDetails, { onSuccess: (session) => { resolve(session); }, onFailure: (err) => { reject(err); }, }); }); } catch (err) { throw err; } } const loginForm = document.getElementById('loginForm'); if (loginForm) { loginForm.addEventListener('submit', async (event) => { event.preventDefault(); const email = document.getElementById('loginUseremail').value; const password = document.getElementById('loginPassword').value; try { const session = await signInUser(email, password); const jwtToken = session.getIdToken().getJwtToken(); console.log('用户登录成功。JWT Token:', jwtToken); console.log('登录成功:', session); // 登录成功后的操作(例如跳转到仪表盘) } catch (err) { console.error('登录失败:', err); } }); };
排查方向
- 用户名匹配问题:检查Cognito用户池是否将邮箱设为用户名。部分用户池注册时用邮箱,但实际存储的用户名是独立字段,需用用户名而非邮箱登录。
- 应用客户端认证流程:确认Cognito应用客户端已启用
ALLOW_USER_PASSWORD_AUTH流程,未禁用用户名密码登录方式。 - 用户状态检查:在Cognito控制台查看用户状态,若为
FORCE_CHANGE_PASSWORD,需先修改密码才能正常登录。 - 密码规则验证:确认登录密码符合用户池设置的密码规则(如大小写、特殊字符、长度),避免注册时密码符合要求但登录输入时出现细微错误。
- 库版本兼容性:尝试更新
amazon-cognito-identity-js到最新版本,旧版本可能存在认证逻辑的兼容性问题。 - 大小写敏感性:Cognito用户名(邮箱)可能区分大小写,确认登录输入的邮箱大小写与注册时完全一致。
内容的提问来源于stack exchange,提问作者Farid
相关产品推荐
相关产品推荐

