Amplify Gen 2 Post-Confirmation Lambda触发器未触发问题求助
排查Amplify Gen 2 Post-Confirmation Lambda触发器未触发问题
按照Amplify Gen 2官方文档配置post-confirmation Lambda触发器,预期用户验证账户后触发函数创建关联UserProfile实体,但部署后函数未触发。以下是配置步骤:
配置步骤
- 更新
amplify/data/resource.ts中的用户资料数据模型:
const schema = a.schema({ UserProfile: a .model({ name: a.string().required(), profileOwner: a.string(), ... }) .authorization(allow => [ allow.ownerDefinedIn('profileOwner') ] ), ... }) .authorization((allow) => [allow.resource(postConfirmation)]);
- 创建
amplify/auth/post-confirmation/resource.ts定义函数:
import { defineFunction } from '@aws-amplify/backend'; export const postConfirmation = defineFunction({ name: 'post-confirmation', });
- 创建处理程序文件
amplify/auth/post-confirmation/handler.ts:
import type { PostConfirmationTriggerHandler } from "aws-lambda"; import { type Schema } from "../../data/resource"; import { Amplify } from "aws-amplify"; import { generateClient } from "aws-amplify/data"; import { getAmplifyDataClientConfig } from '@aws-amplify/backend/function/runtime'; import { env } from "$amplify/env/post-confirmation"; const { resourceConfig, libraryOptions } = await getAmplifyDataClientConfig( env ); Amplify.configure(resourceConfig, libraryOptions); const client = generateClient<Schema>(); export const handler: PostConfirmationTriggerHandler = async (event) => { await client.models.UserProfile.create({ email: event.request.userAttributes.email, profileOwner: `${event.request.userAttributes.sub}::${event.userName}`, }); return event; };
- 在
amplify/auth/resource.ts中添加触发器:
export const auth = defineAuth({ ... triggers: { postConfirmation } });
可能的原因与排查方向
1. Auth触发器配置与用户池验证规则问题
- 确认
amplify/auth/resource.ts中已正确导入postConfirmation函数,triggers配置无拼写错误。 - 检查用户池是否开启了账户验证:Post-Confirmation触发器仅在用户完成邮箱/电话验证后触发,若用户注册后直接启用账户(无需验证),触发器不会执行。
2. Lambda函数部署与权限问题
- 登录AWS控制台,进入Lambda服务,确认
post-confirmation函数已成功部署且状态为“活跃”。 - 检查函数执行角色的权限:确保角色拥有访问Amplify Data模型的必要权限(如
dynamodb:PutItem、Amplify相关的Schema访问权限),可通过IAM控制台查看角色的权限策略。
3. Handler代码错误
- 查看Lambda函数的CloudWatch日志:在Lambda详情页的“监控”->“日志”中,检查是否有执行记录或错误信息。
- 必填字段缺失:Schema中
UserProfile的name是必填项,但Handler中未传入该字段,会导致创建操作失败,函数报错终止。需补充name字段,示例:await client.models.UserProfile.create({ name: event.userName || event.request.userAttributes.email.split('@')[0], email: event.request.userAttributes.email, profileOwner: `${event.request.userAttributes.sub}::${event.userName}`, }); - 确认Amplify配置是否正确:检查
getAmplifyDataClientConfig是否成功获取配置,Amplify.configure是否执行正常。
4. Data模型授权配置问题
- 确认
amplify/data/resource.ts中allow.resource(postConfirmation)已正确关联触发器函数,确保Lambda拥有创建UserProfile的权限。 - 检查
profileOwner的格式是否符合ownerDefinedIn的规则,Amplify默认的所有者字段通常为用户的sub值,若使用自定义格式需确保授权规则能正确识别。
内容的提问来源于stack exchange,提问作者noor soreti
相关产品推荐
相关产品推荐

