
AWS Cognito提供了一套完整的用户管理和认证解决方案,其中包括用户邮箱验证功能。在标准流程中,Cognito可以自行发送验证邮件(通过SES),用户点击邮件中的链接或在前端输入收到的验证码后,通常会通过Cognito SDK或API在用户已认证(拥有Access Token)的上下文中完成验证。例如,CognitoIdentityProvider.GetUserAttributeVerificationCode或VerifyUserAttribute等API都需要有效的用户访问令牌(Access Token)来操作。
然而,在某些场景下,开发者可能需要更高度的定制化:
在上述第三种情况下,Cognito并未直接提供一个API,允许后端仅凭用户名和验证码,在没有用户Access Token的情况下,以管理员身份验证用户邮箱。例如,AdminUpdateUserAttributes可以修改用户属性,但它并非用于验证码的校验。而像GetUserAttributeVerificationCode这样的API,其设计初衷是让已认证的用户请求或验证自己的属性,因此需要Access Token。
鉴于Cognito在无用户访问令牌场景下,缺乏直接的验证码校验API,最实际且灵活的解决方案是:由后端系统自主生成、存储、发送和验证邮箱验证码。 一旦验证码在后端成功校验,再通过Cognito的管理员API更新用户邮箱的验证状态。
在Cognito Lambda Hook中生成并发送自定义验证码: 当用户注册或请求邮箱验证时,Cognito会触发Custom Message Lambda Trigger。在这个Lambda函数中,您可以:
// 示例:Custom Message Lambda Trigger 中的概念代码
const generateVerificationCode = () => {
// 生成一个随机的6位数字验证码
return Math.floor(100000 + Math.random() * 900000).toString();
};exports.handler = async (event) => { if (event.triggerSource === 'CustomMessage_SignUp' || event.triggerSource === 'CustomMessage_ResendCode') { const username = event.userName; const email = event.request.userAttributes.email; const verificationCode = generateVerificationCode();
// TODO: 将 verificationCode 存储到您的数据库/Redis中,并关联到 username/email,设置过期时间
console.log(`Generated code for ${email}: ${verificationCode}`);
// 构建验证链接,发送给用户
const verificationLink = `https://my-frontend.com/verify-email?code=${verificationCode}&email=${encodeURIComponent(email)}`;
// TODO: 调用您的自定义邮件服务发送邮件,邮件内容包含 verificationLink 或 verificationCode
event.response.emailMessage = `您的验证码是:${verificationCode}。或者点击链接验证:${verificationLink}`;
event.response.emailSubject = '请验证您的邮箱';
}
return event;};
前端接收并提交验证信息: 用户收到邮件后,通过点击链接或手动输入验证码,前端将验证码和用户标识(如邮箱或用户名)发送到您的后端API接口。
后端验证并更新Cognito用户状态: 您的后端API接收到验证请求后:
const AWS = require('aws-sdk');
const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
/**
* 在后端验证自定义验证码,并在Cognito中标记邮箱为已验证。
* @param {string} userPoolId Cognito用户池ID
* @param {string} username Cognito用户名 (通常是邮箱或用户ID)
* @param {string} submittedCode 用户提交的验证码
*/
async function verifyEmailAndMarkAsVerified(userPoolId, username, submittedCode) {
// 步骤1: 从您的数据库/Redis中获取存储的验证码
// 假设您有一个函数来获取存储的验证码和其过期时间
// const storedVerificationData = await getStoredCodeFromDB(username);
// if (!storedVerificationData || storedVerificationData.code !== submittedCode || isExpired(storedVerificationData.expiryTime)) {
// throw new Error('Invalid or expired verification code.');
// }
// 实际应用中,这里会进行数据库查询和验证码匹配逻辑
console.log(`Verifying code for ${username}...`);
// 模拟验证成功
const verificationSuccessful = true; // 替换为实际的验证逻辑
if (verificationSuccessful) {
const params = {
UserAttributes: [{
Name: 'email_verified',
Value: 'true'
}],
UserPoolId: userPoolId,
Username: username
};
try {
await cognitoidentityserviceprovider.adminUpdateUserAttributes(params).promise();
console.log(`User ${username} email marked as verified in Cognito.`);
// TODO: 从数据库中删除或标记已使用的验证码
} catch (error) {
console.error(`Error updating user attributes for ${username}:`, error);
throw error;
}
} else {
throw new Error('Verification code mismatch or other validation error.');
}
}
// 示例后端API路由调用 (Node.js Express 框架概念)
// app.post('/api/verify-email', async (req, res) => {
// const { email, code } = req.body;
// const userPoolId = 'YOUR_COGNITO_USER_POOL_ID'; // 从环境变量或配置中获取
// try {
// // 需要根据email找到Cognito的username,如果username不是email本身
// // 假设username就是email
// await verifyEmailAndMarkAsVerified(userPoolId, email, code);
// res.status(200).json({ message: 'Email verified successfully.' });
// } catch (error) {
// res.status(400).json({ error: error.message });
// }
// });尽管AWS Cognito在集成自定义邮件服务时,并未提供直接的“管理员”API来验证其自身生成的验证码而无需用户访问令牌,但通过在后端自主管理验证码流程,我们依然能够实现高度定制化的邮箱验证功能。这种方法涉及在Lambda Hook中生成并存储验证码,通过自定义邮件服务发送,并在后端接收用户提交的验证码后进行校验,最终通过AdminUpdateUserAttributes更新Cognito中用户的邮箱验证状态。这不仅解决了特定场景下的技术难题,也为应用程序带来了更大的灵活性和控制力。
以上就是AWS Cognito与自定义邮件服务集成:无需用户访问令牌的邮箱验证策略的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号