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

.NET授权在AWS Lambda中失效的原因排查与解决建议

问题描述

我有一个运行.NET Web API的AWS Lambda函数,本地通过Cognito实现的JWT认证可正常工作,但将其以容器形式部署到AWS后,即使不传入token,受保护的端点仍返回200响应及正确内容。已尝试所有能想到的方法,仍毫无头绪,求思路或建议。

Dockerfile 参考

# Build Stage
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src

# Step 1: Copy the project file and restore dependencies
COPY CloudWayfinder.CloudWayfinderApi.csproj ./
RUN echo "Step 1: Restoring dependencies..." \
    && ls -la /src \
    && dotnet restore "CloudWayfinder.CloudWayfinderApi.csproj"

# Step 2: Copy the rest of the application and build
COPY . ./
RUN echo "Step 2: Building application..." \
    && dotnet build "CloudWayfinder.CloudWayfinderApi.csproj" --configuration Release --output /app/build

# Publish Stage
FROM build AS publish
RUN echo "Step 3: Publishing application..." \
    && dotnet publish "CloudWayfinder.CloudWayfinderApi.csproj" \
        --configuration Release \
        --runtime linux-x64 \
        --self-contained false \
        --output /app/publish \
        -p:PublishReadyToRun=true || (echo "dotnet publish failed!" && exit 1)

# Runtime Stage
FROM public.ecr.aws/lambda/dotnet:8 AS final
WORKDIR /var/task

# Copy published files to /var/task
COPY --from=publish /app/publish .

# Debug: Check runtime directory
RUN echo "Step 4: Checking runtime directory..." && ls -la /var/task

# Specify the Lambda handler
CMD ["CloudWayfinder.CloudWayfinderApi::CloudWayfinder.CloudWayfinderApi.LambdaEntryPoint::FunctionHandlerAsync"]

本地入口点代码

public class LocalEntryPoint
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Lambda入口点代码

public class LambdaEntryPoint : APIGatewayHttpApiV2ProxyFunction
{
    protected override void Init(IWebHostBuilder builder)
    {
        builder
            .UseStartup<Startup>();
    }
}
排查思路
  • 核对环境变量:确认Lambda容器的环境变量(如Cognito的Authority、Audience配置)和本地一致,若这些配置缺失,JWT认证中间件可能会静默跳过验证。
  • 检查认证中间件注册:查看Startup.cs中的AddJwtBearer配置,确保没有针对Lambda环境的条件判断导致认证中间件未启用。
  • 验证请求头传递:在Lambda函数中打印入参的请求头,确认Authorization头是否真的未传入,或者是否在API Gateway到Lambda的传递过程中丢失。
  • 本地容器复现:将构建好的Docker镜像在本地运行,模拟Lambda的环境变量发起请求,看是否能复现问题,以此排除AWS平台层面的影响。
  • 开启认证日志:在Lambda中启用详细日志记录,查看JWT认证中间件的执行日志,确认是否有错误或跳过验证的情况。
  • 检查Lambda请求转换:确认APIGatewayHttpApiV2ProxyFunction在转换请求时是否正确保留了身份相关的请求头,避免中间件无法读取到token信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 19:32:27