ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

使用 Go Lambda 处理 Amazon Cognito User Pools PreSignup 触发器:事件结构与实战示例

使用 Go Lambda 处理 Amazon Cognito User Pools PreSignup 触发器:事件结构与实战示例 使用 Go Lambda 处理 Amazon Cognito User Pools PreSignup 触发器事件结构与实战示例【免费下载链接】inngestThe leading workflow orchestration platform. Run stateful step functions and AI workflows on serverless, servers, or the edge.项目地址: https://gitcode.com/GitHub_Trending/in/inngest导读本文围绕仓库 vendor/github.com/aws/aws-lambda-go/events/README_Cognito_UserPools_PreSignup.md 中给出的 Cognito User PoolsPreSignup注册前Lambda 触发器示例展开结合 events/cognito.go 中的事件类型定义系统讲解如何在 Go 中接收、解析并响应 PreSignup 事件。读完本文你将掌握CognitoEventUserPoolsPreSignup事件的完整结构、各字段含义与 JSON 对应关系能够编写一个可在本地调试、可部署到 AWS Lambda 的注册前校验处理器并理解AutoConfirmUser、AutoVerifyEmail、AutoVerifyPhone三个响应字段如何改变 Cognito 的注册流程走向。一、PreSignup 触发器是什么AWS Cognito User Pools 允许开发者在用户注册流程的关键节点挂载 Lambda 触发器Trigger。其中PreSignup注册前触发器会在用户提交注册信息之后、用户池正式创建用户之前被调用是用户进入系统前的最后一道自定义逻辑关卡。从源码注释可以确认其语义见 events/cognito.goCognitoEventUserPoolsPreSignup is sent by AWS Cognito User Pools when a user attempts to register (sign up), allowing a Lambda to perform custom validation to accept or deny the registration request.也就是说它允许开发者执行两类自定义操作自定义校验例如校验邀请码、检查邮箱域名白名单、风控规则等不满足条件时返回错误拒绝注册改写注册结果通过修改响应对象决定是否跳过邮箱/手机验证、是否自动确认用户。在 Go 生态中这一能力通过github.com/aws/aws-lambda-go提供的events包实现该依赖以 v1.41.0 版本引入当前仓库见 go.mod事件类型源码位于 vendor/github.com/aws/aws-lambda-go/events/cognito.go。二、事件结构从 JSON 到 Go 结构体PreSignup 事件在events包中被建模为CognitoEventUserPoolsPreSignup结构体其定义位于 vendor/github.com/aws/aws-lambda-go/events/cognito.gotype CognitoEventUserPoolsPreSignup struct { CognitoEventUserPoolsHeader Request CognitoEventUserPoolsPreSignupRequest json:request Response CognitoEventUserPoolsPreSignupResponse json:response }它内嵌了一个公共头结构并包含request与response两个部分。2.1 公共头CognitoEventUserPoolsHeader所有 Cognito User Pools 触发器事件共享同一套头部信息定义于 vendor/github.com/aws/aws-lambda-go/events/cognito.gotype CognitoEventUserPoolsHeader struct { Version string json:version TriggerSource string json:triggerSource Region string json:region UserPoolID string json:userPoolId CallerContext CognitoEventUserPoolsCallerContext json:callerContext UserName string json:userName }各字段含义如下字段JSON 键说明Versionversion事件版本号标识触发器的协议版本TriggerSourcetriggerSource触发来源PreSignup 阶段对应值为PreSignUp_SignUp普通注册或PreSignUp_AdminCreateUser管理员创建用户Regionregion用户池所在的 AWS 区域UserPoolIDuserPoolId用户池的唯一标识CallerContextcallerContext调用上下文内含awsSdkVersion与clientId见CognitoEventUserPoolsCallerContext源码UserNameuserName发起注册的用户名2.2 请求体CognitoEventUserPoolsPreSignupRequesttype CognitoEventUserPoolsPreSignupRequest struct { UserAttributes map[string]string json:userAttributes ValidationData map[string]string json:validationData ClientMetadata map[string]string json:clientMetadata }定义见 vendor/github.com/aws/aws-lambda-go/events/cognito.go三个字段均为字符串到字符串的映射UserAttributes用户在注册时提交的用户属性如email、phone_number、custom:xxx自定义属性是校验逻辑的主要数据来源ValidationData注册请求中携带的验证数据通常来自客户端与注册请求一同提交的键值对ClientMetadata通过SignUpAPI 的ClientMetadata参数透传的客户端元数据可用于传递设备指纹、推广渠道标识等额外信息。2.3 响应体CognitoEventUserPoolsPreSignupResponsetype CognitoEventUserPoolsPreSignupResponse struct { AutoConfirmUser bool json:autoConfirmUser AutoVerifyEmail bool json:autoVerifyEmail AutoVerifyPhone bool json:autoVerifyPhone }定义见 vendor/github.com/aws/aws-lambda-go/events/cognito.go。这是整个 PreSignup 触发器“改写流程”的关键三个布尔开关分别控制字段JSON 键置为true的效果AutoConfirmUserautoConfirmUser自动确认用户跳过“未确认UNCONFIRMED”状态注册即生效AutoVerifyEmailautoVerifyEmail自动将邮箱标记为已验证跳过邮箱验证环节AutoVerifyPhoneautoVerifyPhone自动将手机号标记为已验证跳过短信验证环节三者可以独立或组合开启例如“免验证直接登录”的场景可全部置为true。三、官方示例解读接收事件并写日志原文档 README_Cognito_UserPools_PreSignup.md 给出了一段完整的示例函数其核心思路是以事件结构体作为 handler 入参修改响应字段后再原样返回。package main import ( fmt github.com/aws/aws-lambda-go/events github.com/aws/aws-lambda-go/lambda ) // handler is the lambda handler invoked by the lambda.Start function call func handler(event events.CognitoEventUserPoolsPreSignup) (events.CognitoEventUserPoolsPreSignup, error) { fmt.Printf(PreSignup of user: %s\n, event.UserName) event.Response.AutoConfirmUser true return event, nil } func main() { lambda.Start(handler) }这段代码有三个要点值得注意入口约定main函数通过lambda.Start(handler)注册 handler这是 aws-lambda-go 运行时runtime的标准启动方式事件即入参handler 直接接收events.CognitoEventUserPoolsPreSignup运行时负责完成 JSON 反序列化同时文档指出任何写入stdout或stderr的内容都会被 AWS 收集为CloudWatch Logs 日志事件因此fmt.Printf即可完成打点观测返回即响应handler 将修改后的整个事件对象返回Cognito 从response字段读取结果——这里将AutoConfirmUser置为true等价于“该用户注册即自动确认”。event.UserName直接来自内嵌的CognitoEventUserPoolsHeader字段这也是示例中无需额外解包即可访问的原因。四、深入实战完整可运行的增强示例官方示例只覆盖“自动确认”一种场景。下面给出一个增强版本演示如何同时使用请求体中的属性数据做条件校验、组合设置三个响应开关并通过返回错误拒绝非法注册package main import ( errors fmt strings github.com/aws/aws-lambda-go/events github.com/aws/aws-lambda-go/lambda ) func handler(event events.CognitoEventUserPoolsPreSignup) (events.CognitoEventUserPoolsPreSignup, error) { // 1. 读取公共头信息 fmt.Printf(trigger%s userPool%s region%s user%s\n, event.TriggerSource, event.UserPoolID, event.Region, event.UserName) // 2. 从请求体读取用户属性做自定义校验 email : event.Request.UserAttributes[email] // 示例规则非公司邮箱域名的注册直接拒绝返回错误即拒绝注册 if !strings.HasSuffix(email, example.com) { return event, errors.New(registration denied: email domain not allowed) } // 示例规则校验客户端元数据中的邀请码 if event.Request.ClientMetadata[inviteCode] ! INNGEST-2024 { return event, errors.New(registration denied: invalid invite code) } // 3. 组合设置响应开关 event.Response.AutoConfirmUser true // 自动确认用户 event.Response.AutoVerifyEmail true // 免邮箱验证 // event.Response.AutoVerifyPhone true // 如适用可同样开启 return event, nil } func main() { lambda.Start(handler) }该示例完整覆盖了 PreSignup 处理器的主要职责面读头通过内嵌字段获取TriggerSource、UserPoolID、Region、UserName可用于区分PreSignUp_SignUp与PreSignUp_AdminCreateUser两种触发来源走不同的校验策略读请求从UserAttributes、ValidationData、ClientMetadata三个映射中取数做业务校验拒绝返回非 nil 错误即表示拒绝注册Cognito 会中止用户创建放行并改写设置响应字段返回修改后的事件让 Cognito 按新的开关状态继续流程。五、事件触发与本地调试5.1 在 Cognito 用户池中配置触发器要使用该 Lambda 函数需在 AWS Console 的Cognito → User Pools → 选择用户池 → Triggers页面中将Pre sign-up触发器绑定到上述函数对应官方文档提及的触发器设置指引。配置完成后Cognito 会在用户提交注册时自动调用该 Lambda。5.2 用样例事件在本地跑通逻辑开发阶段可以在本地构造与 AWS 实际下发一致的 JSON 事件来验证 handler无需真实验证码或 AWS 账号。下面是一份符合CognitoEventUserPoolsPreSignupJSON 结构的样例事件{ version: 1, triggerSource: PreSignUp_SignUp, region: us-east-1, userPoolId: us-east-1_example, userName: alice, callerContext: { awsSdkVersion: aws-sdk-unknown-unknown, clientId: example-client-id }, request: { userAttributes: { email: aliceexample.com, custom:plan: pro }, validationData: {}, clientMetadata: { inviteCode: INNGEST-2024 } }, response: { autoConfirmUser: false, autoVerifyEmail: false, autoVerifyPhone: false } }将 JSON 字段与 cognito.go 中的 struct tag 逐一对照可以看到顶层userName落在内嵌头结构request与response分别反序列化到CognitoEventUserPoolsPreSignupRequest和CognitoEventUserPoolsPreSignupResponse三层结构完全对应。本地调试时可以直接将这段 JSON 存入文件并解析后手动调用 handler或者编写针对 handler 的单元测试func TestHandler(t *testing.T) { evt : events.CognitoEventUserPoolsPreSignup{ CognitoEventUserPoolsHeader: events.CognitoEventUserPoolsHeader{ UserName: alice, }, Request: events.CognitoEventUserPoolsPreSignupRequest{ UserAttributes: map[string]string{email: aliceexample.com}, }, } resp, err : handler(evt) if err ! nil { t.Fatalf(unexpected error: %v, err) } if !resp.Response.AutoConfirmUser { t.Error(expected AutoConfirmUser to be true) } }六、与其他 Cognito 触发器的关系PreSignup 并不是唯一的用户池触发器。从 events/cognito.go 的源码看events包为整个用户池触发器族提供了结构一致的事件类型它们共享同一个CognitoEventUserPoolsHeader内嵌头再各自搭配独立的 Request/Response 结构触发器Go 类型触发时机典型用途PreSignupCognitoEventUserPoolsPreSignup用户提交注册后、创建用户前自定义校验、自动确认、跳过验证PreAuthenticationCognitoEventUserPoolsPreAuthentication用户提交登录信息后自定义校验决定是否放行登录PostAuthenticationCognitoEventUserPoolsPostAuthentication用户认证成功后审计、埋点等附加逻辑PostConfirmationCognitoEventUserPoolsPostConfirmation用户确认成功后发送欢迎消息、初始化用户数据PreTokenGenCognitoEventUserPoolsPreTokenGen用户获取凭证时增删改 token claimsMigrateUserCognitoEventUserPoolsMigrateUser用户不存在于用户池时从外部目录迁移用户理解这一族关系有助于复用同一套“读头 读请求 改写响应 返回事件”的处理模式例如把 PreSignup 示例中的 handler 签名换成CognitoEventUserPoolsPostConfirmation即可快速扩展出一个注册后处理函数。仓库中与 PreSignup 同目录的 README_Cognito_UserPools_PreAuthentication.md、README_Cognito_UserPools_PostConfirmation.md、README_Cognito_UserPools_PreTokenGen.md 等文档分别对上述触发器给出了对应的示例函数可作为进阶阅读材料。七、小结事件入口PreSignup 触发器的 Go 事件类型为events.CognitoEventUserPoolsPreSignup由 events/cognito.go 定义整体由内嵌公共头、request、response三部分组成数据来源用户属性、验证数据、客户端元数据分别映射到UserAttributes、ValidationData、ClientMetadata三个map[string]string流程改写AutoConfirmUser、AutoVerifyEmail、AutoVerifyPhone三个布尔开关决定了注册是否自动确认、是否跳过邮箱/手机验证拒绝注册handler 返回非 nil 错误即可拒绝本次注册部署与调试在 Cognito 用户池 Triggers 面板绑定 Pre sign-up 触发器本地可用与 AWS 一致的 JSON 样例事件直接验证 handler 逻辑stdout/stderr输出会自动进入 CloudWatch Logs。【免费下载链接】inngestThe leading workflow orchestration platform. Run stateful step functions and AI workflows on serverless, servers, or the edge.项目地址: https://gitcode.com/GitHub_Trending/in/inngest创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表