You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在serverless-offline中本地测试Cognito触发的Lambda函数

Cognito 认证触发器Lambda本地及CI测试方案咨询
  • 开发目标:为自定义认证流程开发3个Cognito AuthChallenge类型的Lambda触发器,需基于serverless-offline在本地Node.js环境完成开发调试,且调试逻辑可直接复用于CI/CD流水线的Jest测试
  • 核心要求:无需修改生产业务代码即可传入符合Cognito规范的触发器事件调用Lambda,不接受为适配API Gateway事件重写处理函数的方案;优先支持原生cognitoUserPool类型的事件配置,也可接受自定义事件Mock方案

生产环境业务代码示例

现有处理函数直接引入aws-lambda包提供的VerifyAuthChallengeResponseTriggerEvent类型,无API Gateway相关适配逻辑:

import {
    VerifyAuthChallengeResponseTriggerEvent,
    VerifyAuthChallengeResponseTriggerHandler
} from "aws-lambda/trigger/cognito-user-pool-trigger/verify-auth-challenge-response";

export const verifyChallengeHandler: VerifyAuthChallengeResponseTriggerHandler =
    async (event: VerifyAuthChallengeResponseTriggerEvent):
        Promise<VerifyAuthChallengeResponseTriggerEvent> => {

        event.response.answerCorrect = event.request.privateChallengeParameters["code"] == event.request.challengeAnswer;

        return event;
    };

已验证的不合理方案

目前公开的serverless-offline使用示例大多搭配API Gateway的http事件,给函数配置如下http事件后,本地确实可以正常触发函数:

events: [
    {
        http: {
            method: "post",
            path: "auth-verify",
            cors: {
                origin: '*',
                headers:[
                    "Content-Type",
                    "X-Amz-Date",
                    "X-Amz-Security-Token",
                    "Authorization",
                    "X-Api-Key",
                    "X-Requested-With",
                    "Accept",
                ],
                allowCredentials: true,
            },
        },
    },
],

但该方案必须重写处理函数以适配API Gateway事件类型,会导致测试环境与生产环境代码不一致,重写后的代码结构如下,不符合要求:

import { ValidatedEventAPIGatewayProxyEvent } from '@libs/apiGateway';
import { middyfy } from '@libs/lambda';
import schema from './schema';


const verifyChallengeHandler: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async(event) => {
   // 适配API Gateway的业务逻辑改写
}

期望的配置形式

希望直接在serverless配置的functions节点下使用原生cognitoUserPool类型的事件配置,而非http事件配置:

events: [
    {
        cognitoUserPool: {
            pool: <some_pool_name>,
            trigger: 'VerifyAuthChallengeResponse' as const,
            existing: false,
        },
    },
]

需要获取可行的Serverless配置方式、对应本地调用命令,实现本地环境和Jest测试中无需修改业务代码即可传入正确Cognito事件调用Lambda的效果;若采用自定义Mock事件方案,也需要明确Mock事件的指定方法。


内容的提问来源于stack exchange,提问作者Kuba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 18:00:52