Skip to Content
Cloud Engineering Academy
4. API Development & Integration

Lambda integrations for API Gateway

Connect .NET 10 Lambda functions to REST and HTTP APIs: proxy vs custom integrations, payload format 1.0 vs 2.0, ASP.NET Core on Lambda, error mapping, timeouts and cold starts, then build Lab 4.2 (HTTP API + Lambda + Cognito JWT authorizer with scopes).

intermediate⏱ 2 h 🟢 FreeDVA-C03SAA-C03SCS-C03

Assumes: .NET 10 LTS · Lambda runtime dotnet10 · Amazon.Lambda.AspNetCoreServer.Hosting 2.2.1 · Amazon.Lambda.Annotations 2.4.2 · Amazon.Lambda.Tools 7.0.0 · Amazon.CDK.Lib 2.277.0 · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-17.

Learning objectives

By the end of this lesson you can:

  • Explain the difference between a Lambda proxy integration and a custom (non-proxy) integration on a REST API, and why HTTP APIs offer only proxy integrations.
  • Compare HTTP API payload format 1.0 and 2.0 and pick the matching LambdaEventSource for ASP.NET Core on Lambda.
  • Predict what the client sees when your code throws, times out or returns ProblemDetails, and fix it with gateway responses or code.
  • Reduce cold starts for .NET with memory sizing, ARM64, SnapStart or Native AOT, and know which combinations are supported.
  • Deploy Lab 4.2: an HTTP API with a dotnet10 Lambda behind a Cognito JWT authorizer with scopes, test it with curl and PowerShell, and tear it down.

Prerequisites

Why this matters in banking

A Harbourline developer deploys the Accounts API to Lambda behind API Gateway. In testing, every exception becomes {"message": "Internal server error"} with status 502 and no correlation ID, so the support desk cannot trace complaints. A slow core banking call makes some requests fail at 29 seconds while Lambda keeps running for 60 and bills for it. And on Monday morning the first customers wait three seconds for a balance because of cold starts. None of these are bugs in the business logic; they are integration details. This lesson makes them predictable.

The idea in plain language

API Gateway turns an HTTP request into a JSON event, invokes your Lambda function with it, and turns the function's JSON result back into an HTTP response.

  • Proxy integration (AWS_PROXY): API Gateway passes the whole request (method, path, headers, query, body, auth claims) to the function unchanged and expects a response object with statusCode, headers and body. Your code owns the HTTP contract.
  • Custom (non-proxy) integration (AWS, REST APIs only): you write mapping templates (Velocity Template Language, VTL) that build whatever input the function needs, and integration responses that map the function's output and errors back to HTTP status codes. API Gateway owns the HTTP contract.

Analogy: a proxy integration is forwarding a customer's letter unopened to the right department, which writes the reply itself. A custom integration is the post room opening the letter, filling in an internal form, and later rewriting the department's internal memo into a customer letter. More control, more paperwork, more places for mistakes.

For .NET developers there is a third layer: you can run a whole ASP.NET Core app inside one Lambda function. The Amazon.Lambda.AspNetCoreServer.Hosting package translates each API Gateway event into an HttpContext, so routing, model binding, authentication, ProblemDetails and middleware work as they do on Kestrel.

What problem the AWS service solves

Proxy vs custom integrations on REST APIs

Proxy (AWS_PROXY)Custom (AWS)
Event shapeFixed: APIGatewayProxyRequest (payload 1.0)Whatever your request mapping template produces
ResponseFunction returns statusCode, headers, bodyIntegration responses map output; status chosen by regex on errorMessage
ErrorsFunction decides status; a crash or malformed response gives 502Unmapped Lambda errors come back as 200 OK with the error JSON unless you add integration responses
Response streamingSupportedNot supported
Use whenAlmost always (ASP.NET Core, Annotations)Legacy contracts, transforming SOAP-ish payloads, calling a function that knows nothing about HTTP

HTTP API payload format 1.0 vs 2.0

HTTP APIs support only proxy-style Lambda integrations but offer two event formats. The console defaults to 2.0; the CLI, CloudFormation and SDKs make you choose payloadFormatVersion explicitly, and the CDK HttpLambdaIntegration defaults to 2.0.

1.02.0
.NET event typeAPIGatewayProxyRequestAPIGatewayHttpApiV2ProxyRequest
Repeated headers / query stringsmultiValueHeaders, multiValueQueryStringParametersJoined with commas in headers and queryStringParameters
Pathpath, resourcerawPath, rawQueryString, routeKey
CookiesInside headersSeparate cookies array; response cookies become set-cookie headers
JWT claimsrequestContext.authorizer.claimsrequestContext.authorizer.jwt.claims and .scopes
ResponseMust return statusCode etc.May return plain JSON; API Gateway then assumes 200 and application/json
Custom domain mappingpath includes the API mappingrawPath does not include the API mapping

Do not confuse payload format with the simple response option for HTTP API Lambda authorizers (isAuthorized: true/false); that is a separate setting covered in Lambda authorizers.

ASP.NET Core on Lambda

builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi);

LambdaEventSource has three values: RestApi (payload 1.0 from a REST API), HttpApi (HTTP API payload 2.0) and ApplicationLoadBalancer. Outside Lambda the call does nothing, so the same project runs on Kestrel locally, in a container on Fargate, or in Lambda. The deployed function's handler is simply the assembly name. Pick the event source that matches the integration: HttpApi with a 1.0 integration fails to deserialize requests.

The Lambda Annotations framework (Amazon.Lambda.Annotations 2.4.2) is the lighter alternative: one Lambda function per method, generated by a source generator, with attributes instead of a web host.

FxRateFunctions.cs
using Amazon.Lambda.Annotations;
using Amazon.Lambda.Annotations.APIGateway;

namespace Harbourline.FxRates;

public sealed class FxRateFunctions
{
    private static readonly Dictionary<string, decimal> GbpRates = new() { ["EUR"] = 1.1650m, ["USD"] = 1.2710m };

    [LambdaFunction(MemorySize = 512, Timeout = 10)]
    [HttpApi(LambdaHttpMethod.Get, "/v1/fx-rates/GBP/{quoteCurrency}")]
    public IHttpResult GetRate([FromRoute] string quoteCurrency) =>
        GbpRates.TryGetValue(quoteCurrency.ToUpperInvariant(), out var rate)
            ? HttpResults.Ok(new { baseCurrency = "GBP", quoteCurrency, rate })
            : HttpResults.NotFound();
}

[RestApi(...)] works the same way for REST APIs. The generator also writes the functions into serverless.template for SAM or dotnet lambda deploy-serverless. Choose ASP.NET Core when you already have an API (or want it portable to containers); choose Annotations for small, fast-starting functions.

Error mapping: what the client actually sees

What happensREST API (proxy)HTTP API (payload 2.0)
Your code returns 400/404/409 ProblemDetailsPassed through unchangedPassed through unchanged
An ASP.NET Core endpoint throws, UseExceptionHandler is on500 ProblemDetails from your appSame
The handler itself crashes or returns a malformed response502 {"message": "Internal server error"}{"message":"Internal Server Error"} (status 500 ⚠ VERIFY)
Integration timeout (29 s REST, 30 s HTTP)504 (INTEGRATION_TIMEOUT gateway response)503 ⚠ VERIFY
API Gateway lacks lambda:InvokeFunction permission500{"message":"Internal Server Error"}
Non-proxy integration, error not mapped200 with the Lambda error JSONNot applicable

The lesson: keep errors inside ASP.NET Core (ProblemDetails with traceId and correlationId), and on REST APIs customise the gateway responses (DEFAULT_5XX, INTEGRATION_TIMEOUT, THROTTLED, UNAUTHORIZED) so even gateway-generated errors look like RFC 9457 problem documents. HTTP APIs have no custom gateway responses.

Timeouts: two clocks

API Gateway's integration timeout (REST: up to 29 s by default; HTTP: 30 s maximum) and the Lambda function timeout (up to 15 minutes) run independently. If the gateway gives up first, the client gets 504/503 but the function keeps running and is billed, and any side effect (a statement request, a payment) still happens. Set the Lambda timeout slightly below the gateway timeout (for example 25 s), set HttpClient timeouts below that, and make writes idempotent (see Idempotency keys).

Cold starts, SnapStart and Native AOT

A cold start happens when Lambda creates a new execution environment: download code, start the .NET runtime, run your Program.cs (DI container, configuration, JWKS fetch). ASP.NET Core adds hundreds of milliseconds to that.

OptionWhat it doesNotes for .NET
More memory (1024–2048 MB)More CPU during initOften the cheapest fix; measure with the Init Duration log line
ARM64 (Graviton)Lower price per GB-secondBuild for linux-arm64
ReadyToRunPre-compiles ILLarger package, faster JIT
SnapStartSnapshots the initialised environment when you publish a versionSupported on .NET 8 and later managed runtimes; only on published versions/aliases; not with provisioned concurrency, EFS or ephemeral storage over 512 MB; caching and restore are billed for .NET; regenerate unique values after restore
Native AOTCompiles to a native binaryRuns on the managed .NET runtime; needs an Amazon Linux 2023 build (Docker), source-generated JSON, and trimming-safe libraries; ASP.NET Core minimal APIs work with care
Provisioned concurrencyKeeps environments warmSteady hourly cost; cannot be combined with SnapStart

SnapStart and Native AOT target the same problem; AWS documents them separately and does not document combining them, so pick one per function.

Deploying .NET functions

  • dotnet lambda deploy-function / dotnet lambda package / dotnet lambda delete-function (Amazon.Lambda.Tools 7.0.0) for single functions.
  • dotnet lambda deploy-serverless or sam build && sam deploy for serverless.template / SAM templates.
  • CDK (this lab) or Terraform for everything else, packaging with dotnet lambda package.

Permissions

API Gateway calls Lambda as the service principal apigateway.amazonaws.com, so the function needs a resource-based policy allowing lambda:InvokeFunction, restricted with a source ARN such as arn:aws:execute-api:us-east-1:111122223333:a1b2c3d4e5/*/GET/v1/accounts. The console adds it for you; the CLI, CloudFormation and SDKs do not; the CDK HttpLambdaIntegration adds one scoped to each route.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Azure Functions HTTP triggerLambda behind API Gateway (proxy) or a Lambda function URLThe HTTP front door is a separate service with its own timeout, auth and pricing
APIM set-backend-service + policies transforming payloadsREST API custom integration with VTL mapping templatesVTL instead of APIM policy expressions; HTTP APIs cannot transform bodies
ASP.NET Core on App ServiceASP.NET Core on Lambda via AddAWSLambdaHostingSame code; one request per execution environment at a time
Functions isolated worker attributes ([Function], [HttpTrigger])Lambda Annotations ([LambdaFunction], [HttpApi], [RestApi])Source-generated handlers and template
Premium plan pre-warmed instancesProvisioned concurrency or SnapStartSnapStart restores a snapshot instead of keeping instances running
Easy Auth / APIM validate-jwtAPI Gateway JWT/Cognito authorizer + JwtBearer in codeValidate at the edge and in the app

Architecture

Security-boundary view. The token endpoint and the API are public; trust starts at the JWT authorizer, which rejects unsigned, expired, wrong-issuer, wrong-client or wrong-scope tokens before Lambda runs (you are not billed for rejected requests). Inside the function, ASP.NET Core validates the token again (token_use, client_id allow-list, scope) and maps sub to a customer. The function's execution role has only CloudWatch Logs permissions; the resource policy allows invocation only from this API's routes.

Step-by-step implementation

This is Lab 4.2. Folder layout:

lab-4-2/
├── src/Harbourline.Lab42.Api/        Program.cs, Harbourline.Lab42.Api.csproj
├── infra/Harbourline.Lab42.Infra/    Program.cs, HttpApiJwtStack.cs, cdk.json
└── artifacts/                        build output (zip)

Create the API project

dotnet new web -n Harbourline.Lab42.Api -o src/Harbourline.Lab42.Api, then dotnet add package Amazon.Lambda.AspNetCoreServer.Hosting --version 2.2.1 and dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer --version 10.0.15. Replace Program.cs with the code in Complete code.

Package it for ARM64

From src/Harbourline.Lab42.Api: dotnet lambda package -c Release --function-architecture arm64 -o ../../artifacts/hl-m04-l2-accounts.zip.

Deploy the stack

From infra/Harbourline.Lab42.Infra: cdk deploy -c domainPrefix=hl-m04-l2-<yourname> -c owner=<yourname> --profile learn-sandbox. Note the outputs ApiUrl, TokenUrl, ClientId and UserPoolId.

Get a token and call the API

Use the CLI section. Expect 401 without a token, 200 with an accounts.read token, 403 on the statements route (the client lacks statements.write), and a 500 ProblemDetails from the diagnostics route.

Tear down

cdk destroy and run the tag check in Cost and cleanup.

AWS Console instructions

  1. Console → API Gateway → APIs → hl-m04-l2-accounts-api → Routes: each route shows JWT authorization and its scopes.
  2. Authorization → Manage authorizers: the issuer is https://cognito-idp.us-east-1.amazonaws.com/<poolId> and the audience is the app client ID (API Gateway checks client_id when the token has no aud).
  3. Integrations: the Lambda integration shows Payload format version 2.0.
  4. Lambda → Functions → hl-m04-l2-accounts → Configuration → Permissions → Resource-based policy statements: one statement per route, each with a SourceArn condition.
  5. Lambda → Monitor → View CloudWatch logs: look for Init Duration on the first invocation to measure the cold start.

AWS CLI

P="--profile learn-sandbox --region us-east-1"
STACK=hl-m04-l2
out() { aws cloudformation describe-stacks --stack-name $STACK $P \
  --query "Stacks[0].Outputs[?OutputKey=='$1'].OutputValue" --output text; }
API_URL=$(out ApiUrl); TOKEN_URL=$(out TokenUrl); CLIENT_ID=$(out ClientId); POOL_ID=$(out UserPoolId)

# The client secret never goes into outputs; read it on demand.
CLIENT_SECRET=$(aws cognito-idp describe-user-pool-client $P --user-pool-id "$POOL_ID" \
  --client-id "$CLIENT_ID" --query UserPoolClient.ClientSecret --output text)

# 1. No token -> 401 from the JWT authorizer (Lambda is never invoked)
curl -i "$API_URL/v1/accounts"

# 2. Client-credentials token with the read scope (USD 0.00225 per token request)
TOKEN=$(curl -s -u "$CLIENT_ID:$CLIENT_SECRET" \
  -d "grant_type=client_credentials&scope=harbourline-accounts/accounts.read" \
  "$TOKEN_URL" | jq -r .access_token)

# 3. Authorized call -> 200 with CUS-00012345's two accounts
curl -s -H "Authorization: Bearer $TOKEN" "$API_URL/v1/accounts" | jq

# 4. Missing scope -> 403 from API Gateway
curl -i -X POST -H "Authorization: Bearer $TOKEN" \
  "$API_URL/v1/accounts/ACC-0000012345/statement-requests"

# 5. Exception inside ASP.NET Core -> 500 application/problem+json (not a gateway 502)
curl -i -H "Authorization: Bearer $TOKEN" "$API_URL/v1/diagnostics/fail"

# 6. Inspect the resource-based policy the CDK created
aws lambda get-policy --function-name hl-m04-l2-accounts $P --query Policy --output text | jq

PowerShell equivalent for steps 2–3:

$basic = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${CLIENT_ID}:${CLIENT_SECRET}"))
$tok = Invoke-RestMethod -Method Post -Uri $TOKEN_URL -Headers @{ Authorization = "Basic $basic" } `
  -ContentType "application/x-www-form-urlencoded" `
  -Body "grant_type=client_credentials&scope=harbourline-accounts/accounts.read"
Invoke-RestMethod -Uri "$API_URL/v1/accounts" -Headers @{ Authorization = "Bearer $($tok.access_token)" }

If you build the integration by hand instead of CDK, grant the permission yourself:

aws lambda add-permission $P --function-name hl-m04-l2-accounts \
  --statement-id apigw-get-accounts --action lambda:InvokeFunction \
  --principal apigateway.amazonaws.com \
  --source-arn "arn:aws:execute-api:us-east-1:<account-id>:<api-id>/*/GET/v1/accounts"

Infrastructure as Code

infra/Harbourline.Lab42.Infra/HttpApiJwtStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.Apigatewayv2;
using Amazon.CDK.AWS.Cognito;
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.Logs;
using Amazon.CDK.AwsApigatewayv2Authorizers;
using Amazon.CDK.AwsApigatewayv2Integrations;
using Constructs;
using ApiHttpMethod = Amazon.CDK.AWS.Apigatewayv2.HttpMethod;

namespace Harbourline.Lab42.Infra;

public sealed class HttpApiJwtStack : Stack
{
    public HttpApiJwtStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
    {
        var domainPrefix = (string?)Node.TryGetContext("domainPrefix")
            ?? throw new InvalidOperationException("Pass -c domainPrefix=hl-m04-l2-<yourname>");

        var pool = new UserPool(this, "Pool", new UserPoolProps
        {
            UserPoolName = "hl-m04-l2-pool",
            SelfSignUpEnabled = false,
            FeaturePlan = FeaturePlan.ESSENTIALS,
            RemovalPolicy = RemovalPolicy.DESTROY,
        });

        var read = new ResourceServerScope(new ResourceServerScopeProps
            { ScopeName = "accounts.read", ScopeDescription = "Read own accounts" });
        var write = new ResourceServerScope(new ResourceServerScopeProps
            { ScopeName = "statements.write", ScopeDescription = "Request statements" });
        var accountsApi = pool.AddResourceServer("AccountsApi", new UserPoolResourceServerOptions
        {
            Identifier = "harbourline-accounts",
            Scopes = new[] { read, write },
        });

        pool.AddDomain("Domain", new UserPoolDomainOptions
        {
            CognitoDomain = new CognitoDomainOptions { DomainPrefix = domainPrefix },
        });

        var reconClient = pool.AddClient("ReconJobClient", new UserPoolClientOptions
        {
            UserPoolClientName = "hl-m04-l2-recon-job",
            GenerateSecret = true,
            AccessTokenValidity = Duration.Minutes(15),
            OAuth = new OAuthSettings
            {
                Flows = new OAuthFlows { ClientCredentials = true },
                Scopes = new[] { OAuthScope.ResourceServer(accountsApi, read) },
            },
        });

        var issuer = $"https://cognito-idp.{Region}.amazonaws.com/{pool.UserPoolId}";

        var fnLogs = new LogGroup(this, "FnLogs", new LogGroupProps
        {
            LogGroupName = "/aws/lambda/hl-m04-l2-accounts",
            Retention = RetentionDays.ONE_WEEK,
            RemovalPolicy = RemovalPolicy.DESTROY,
        });

        var fn = new Function(this, "AccountsFn", new FunctionProps
        {
            FunctionName = "hl-m04-l2-accounts",
            Runtime = Runtime.DOTNET_10,
            Architecture = Architecture.ARM_64,
            Handler = "Harbourline.Lab42.Api",
            Code = Code.FromAsset("../../artifacts/hl-m04-l2-accounts.zip"),
            MemorySize = 1024,
            Timeout = Duration.Seconds(25),
            LogGroup = fnLogs,
            Environment = new Dictionary<string, string>
            {
                ["Cognito__Issuer"] = issuer,
                ["Cognito__AllowedClientIds__0"] = reconClient.UserPoolClientId,
                ["Demo__ServiceClientId"] = reconClient.UserPoolClientId,
            },
        });

        var api = new HttpApi(this, "Api", new HttpApiProps
        {
            ApiName = "hl-m04-l2-accounts-api",
            CreateDefaultStage = false,
        });

        var stage = new HttpStage(this, "DefaultStage", new HttpStageProps
        {
            HttpApi = api,
            StageName = "$default",
            AutoDeploy = true,
            Throttle = new ThrottleSettings { RateLimit = 20, BurstLimit = 40 },
        });

        var accessLogs = new LogGroup(this, "ApiAccessLogs", new LogGroupProps
        {
            LogGroupName = "/hl-m04-l2/api-access",
            Retention = RetentionDays.ONE_WEEK,
            RemovalPolicy = RemovalPolicy.DESTROY,
        });
        var cfnStage = (CfnStage)stage.Node.DefaultChild!;
        cfnStage.AccessLogSettings = new CfnStage.AccessLogSettingsProperty
        {
            DestinationArn = accessLogs.LogGroupArn,
            Format = "{\"requestId\":\"$context.requestId\",\"route\":\"$context.routeKey\",\"status\":\"$context.status\",\"sub\":\"$context.authorizer.claims.sub\",\"error\":\"$context.integrationErrorMessage\"}",
        };

        var integration = new HttpLambdaIntegration("AccountsIntegration", fn);
        var authorizer = new HttpUserPoolAuthorizer("CognitoJwt", pool, new HttpUserPoolAuthorizerProps
        {
            UserPoolClients = new IUserPoolClient[] { reconClient },
            IdentitySource = new[] { "$request.header.Authorization" },
        });

        AddRoute(api, "/v1/accounts", ApiHttpMethod.GET, integration, authorizer, "harbourline-accounts/accounts.read");
        AddRoute(api, "/v1/accounts/{accountId}/statement-requests", ApiHttpMethod.POST, integration, authorizer, "harbourline-accounts/statements.write");
        AddRoute(api, "/v1/diagnostics/fail", ApiHttpMethod.GET, integration, authorizer, "harbourline-accounts/accounts.read");

        new CfnOutput(this, "ApiUrl", new CfnOutputProps { Value = api.ApiEndpoint });
        new CfnOutput(this, "TokenUrl", new CfnOutputProps
            { Value = $"https://{domainPrefix}.auth.{Region}.amazoncognito.com/oauth2/token" });
        new CfnOutput(this, "ClientId", new CfnOutputProps { Value = reconClient.UserPoolClientId });
        new CfnOutput(this, "UserPoolId", new CfnOutputProps { Value = pool.UserPoolId });
    }

    private static void AddRoute(HttpApi api, string path, ApiHttpMethod method,
        HttpLambdaIntegration integration, HttpUserPoolAuthorizer authorizer, string scope) =>
        api.AddRoutes(new AddRoutesOptions
        {
            Path = path,
            Methods = new[] { method },
            Integration = integration,
            Authorizer = authorizer,
            AuthorizationScopes = new[] { scope },
        });
}
infra/Harbourline.Lab42.Infra/Program.cs
using Amazon.CDK;
using Cdklabs.CdkNag;
using Harbourline.Lab42.Infra;

var app = new App();
var stack = new HttpApiJwtStack(app, "hl-m04-l2", new StackProps
{
    Env = new Amazon.CDK.Environment { Region = "us-east-1" },
});

Tags.Of(app).Add("Project", "cea-lab");
Tags.Of(app).Add("Lab", "m04-l2");
Tags.Of(app).Add("Environment", "learn");
Tags.Of(app).Add("Owner", (string?)app.Node.TryGetContext("owner") ?? "unknown");

// cdk-nag v3: the pack is a CDK validation plugin, and findings are acknowledged with the CDK Validations API.
Validations.Of(app).AddPlugins(new AwsSolutionsChecks(app, new NagPackProps { Verbose = true }));
Validations.Of(stack).Acknowledge(new[]
{
    new Acknowledgment { Id = "AwsSolutions-COG2", Reason = "Lab pool has no human users; MFA is configured in the Cognito lesson." },
    new Acknowledgment { Id = "AwsSolutions-IAM4", Reason = "AWSLambdaBasicExecutionRole is acceptable for a logs-only lab function." },
});

app.Synth();

The project references Amazon.CDK.Lib 2.277.0 and Cdklabs.CdkNag 3.0.2. The integrations and authorizers are part of Amazon.CDK.Lib (stable since CDK v2 moved them out of alpha) under the namespaces Amazon.CDK.AwsApigatewayv2Integrations and Amazon.CDK.AwsApigatewayv2Authorizers. Run cdk synth and read every cdk-nag finding: fix it or acknowledge it with a reason (Validations.Of(...).Acknowledge), never silently.

Complete code

src/Harbourline.Lab42.Api/Harbourline.Lab42.Api.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <AssemblyName>Harbourline.Lab42.Api</AssemblyName>
    <RootNamespace>Harbourline.Lab42.Api</RootNamespace>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Amazon.Lambda.AspNetCoreServer.Hosting" Version="2.2.1" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.15" />
  </ItemGroup>
</Project>
src/Harbourline.Lab42.Api/Program.cs
using System.Security.Claims;
using Amazon.Lambda.AspNetCoreServer.Hosting;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi);
builder.Services.AddProblemDetails();

var issuer = builder.Configuration["Cognito:Issuer"]
    ?? throw new InvalidOperationException("Configure Cognito:Issuer.");
var allowedClients = builder.Configuration.GetSection("Cognito:AllowedClientIds").Get<string[]>() ?? [];
var serviceClientId = builder.Configuration["Demo:ServiceClientId"];

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = issuer;
        options.MapInboundClaims = false;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = issuer,
            ValidateAudience = false,
            ClockSkew = TimeSpan.FromSeconds(60),
        };
        options.Events = new JwtBearerEvents
        {
            OnTokenValidated = context =>
            {
                var principal = context.Principal!;
                if (principal.FindFirstValue("token_use") != "access"
                    || !allowedClients.Contains(principal.FindFirstValue("client_id") ?? string.Empty))
                {
                    context.Fail("Not an access token issued to an allowed client.");
                }
                return Task.CompletedTask;
            },
        };
    });

builder.Services.AddAuthorizationBuilder()
    .AddPolicy("accounts:read", p => p.RequireAssertion(c => HasScope(c.User, "harbourline-accounts/accounts.read")))
    .AddPolicy("statements:write", p => p.RequireAssertion(c => HasScope(c.User, "harbourline-accounts/statements.write")));

var app = builder.Build();

app.UseExceptionHandler();
app.UseStatusCodePages();
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/v1/accounts", (ClaimsPrincipal user) =>
{
    var customerId = user.FindFirstValue("sub") == serviceClientId ? "CUS-00012345" : null;
    if (customerId is null)
    {
        return Results.Problem(statusCode: StatusCodes.Status404NotFound, title: "No customer is linked to this identity.");
    }

    var items = DemoData.Accounts.Where(a => a.CustomerId == customerId).ToArray();
    return Results.Ok(new { items, nextCursor = (string?)null });
}).RequireAuthorization("accounts:read");

app.MapPost("/v1/accounts/{accountId}/statement-requests", (string accountId) =>
    Results.Accepted($"/v1/statement-requests/{Guid.CreateVersion7()}", new { accountId, status = "received" }))
   .RequireAuthorization("statements:write");

app.MapGet("/v1/diagnostics/fail", () =>
{
    throw new InvalidOperationException("Simulated core banking failure.");
}).RequireAuthorization("accounts:read");

app.MapGet("/health/live", () => Results.Ok(new { status = "live" }));

app.Run();

static bool HasScope(ClaimsPrincipal user, string scope) =>
    user.FindFirstValue("scope")?.Split(' ', StringSplitOptions.RemoveEmptyEntries).Contains(scope) == true;

internal sealed record Account(string AccountId, string CustomerId, string Currency, string Product, decimal Balance);

internal static class DemoData
{
    public static readonly Account[] Accounts =
    [
        new("ACC-0000012345", "CUS-00012345", "GBP", "current", 1520.40m),
        new("ACC-0000012346", "CUS-00012345", "EUR", "savings", 8300.00m),
        new("ACC-0000099999", "CUS-00099999", "GBP", "current", 77.10m),
    ];
}

The module project (labs/m04-account-information-api/) grows this into the full Account Information API with an ICustomerDirectory, cursor pagination, idempotency and a REST API with WAF.

Code explained line by line

  1. AddAWSLambdaHosting(LambdaEventSource.HttpApi) — inside Lambda, registers a server that converts HTTP API payload 2.0 events into HttpContext; on your laptop it does nothing, so dotnet run serves on Kestrel.
  2. AddProblemDetails() + UseExceptionHandler() + UseStatusCodePages() — every error leaves the function as an RFC 9457 problem document with a status code, so API Gateway passes it through instead of producing a bare 502/500.
  3. Cognito:Issuer — https://cognito-idp.us-east-1.amazonaws.com/<poolId>; set by the CDK as the environment variable Cognito__Issuer (double underscore = section separator).
  4. options.Authority = issuer — JwtBearer downloads the OIDC discovery document and the JWKS from the issuer and caches the signing keys.
  5. MapInboundClaims = false — keeps sub, scope, client_id, token_use with their JWT names instead of long WS-Federation claim URIs.
  6. ValidateAudience = false — Cognito access tokens have no aud; the client_id allow-list in OnTokenValidated replaces the audience check.
  7. token_use != "access" — rejects Cognito ID tokens, which a careless client might send.
  8. AddAuthorizationBuilder().AddPolicy(...) — scope policies, the same names as the module project (accounts:read, statements:write).
  9. user.FindFirstValue("sub") == serviceClientId — a learning shortcut: in a client-credentials token sub equals the client ID, so we pretend that client is customer CUS-00012345. Real code resolves sub through a customer directory.
  10. Where(a => a.CustomerId == customerId) — ownership is enforced in the query; customer IDs never come from the URL.
  11. Results.Accepted(...) with Guid.CreateVersion7() — returns 202 Accepted and a Location header for an asynchronous statement request.
  12. /v1/diagnostics/fail — throws so you can see a 500 ProblemDetails instead of a gateway error. Never ship such an endpoint.
  13. HasScope — Cognito puts scopes in one space-separated scope claim.
  14. decimal Balance and ISO currency codes — money is never double.
  15. CDK: HttpUserPoolAuthorizer builds a JWT authorizer with issuer = the pool and audience = the listed client IDs.
  16. CDK: AuthorizationScopes on each route — API Gateway returns 403 when none of the route's scopes is in the token.
  17. CDK: HttpLambdaIntegration — payload format 2.0 by default and one lambda:InvokeFunction permission per route, scoped by source ARN.
  18. CDK: Timeout = Duration.Seconds(25) — below the HTTP API's 30-second maximum, so the function stops before the gateway gives up.
  19. CDK: the CfnStage escape hatch sets JSON access logs including $context.integrationErrorMessage, the fastest way to diagnose 500s.

Security considerations

⚠ Learning shortcut — not for production

The lab uses a client-credentials token as a stand-in for a customer, maps it to CUS-00012345, and exposes a /v1/diagnostics/fail route. In production, customer-facing APIs receive user access tokens from the authorization code + PKCE flow, sub is resolved by a customer directory, diagnostic routes do not exist, and the client secret lives in AWS Secrets Manager with rotation — never in shell history.

  • Validate twice. The JWT authorizer stops bad tokens cheaply at the edge; the app re-validates so it stays safe when someone adds a route without an authorizer or calls the function another way.
  • Least privilege for invocation. Keep source-ARN-scoped permissions; a wildcard */*/* lets any route or stage of that API invoke the function.
  • No secrets in environment variables. Issuer and client IDs are not secrets; database passwords and partner keys belong in Secrets Manager.
  • Logs are personal data. Access logs with sub are pseudonymous personal data under UK GDPR; set retention (7 days here) and agree it with your data-protection team.
  • Tracing. Use OpenTelemetry (ADOT) for .NET instrumentation; the X-Ray SDK for .NET is in maintenance mode.

Banking use case

Harbourline's nightly reconciliation job needs read-only access to account lists. It authenticates with a confidential Cognito client restricted to harbourline-accounts/accounts.read, gets a 15-minute token, and calls the HTTP API. If someone later grants the same client statements.write by mistake, the code review of the Cognito client diff (and the scope list on the route) catches it. Customer traffic goes through the module project's REST API with WAF instead; the cheaper HTTP API is reserved for internal machine callers.

Common mistakes

  • Wrong LambdaEventSource. RestApi with an HTTP API 2.0 integration (or the reverse) produces empty paths or 500s. Match the integration.
  • Lambda timeout longer than the gateway timeout. Clients get 503/504 while the function keeps working and billing. Keep Lambda below the gateway.
  • Sending ID tokens. They pass the authorizer if the audience matches, but have no scopes; require scopes on every route and check token_use.
  • Forgetting add-permission outside the console. Symptom: {"message":"Internal Server Error"} and "Invalid permissions on Lambda function" in access logs.
  • Building on Windows for ARM64 Native AOT. AOT must be compiled on Amazon Linux 2023 (the tool uses Docker); switch Docker to Linux containers.

Troubleshooting

SymptomLikely causeFix
401 with a fresh tokenWrong issuer Region/pool, or Bearer prefix missing in a custom headerCompare token iss with the authorizer issuer; send Authorization: Bearer <token>
403 from API GatewayToken lacks every scope listed on the routeRequest the scope in the token call; check the client's allowed scopes
401 from the app but not the gatewayclient_id not in Cognito:AllowedClientIds, or token_use is idFix configuration; use an access token
{"message":"Internal Server Error"}Missing invoke permission or handler crashAdd $context.integrationErrorMessage to access logs; check Lambda logs
invalid_client from the token endpointWrong secret or client not enabled for client credentialsRe-read the secret; check AllowedOAuthFlows
First request slow (2–4 s)Cold startMore memory, ARM64, SnapStart on a published alias, or Native AOT

Cost and cleanup

cost: free for practical purposes: Lambda (1 million requests and 400,000 GB-seconds per month in the free tier), HTTP API requests (USD 1.00 per million) and Cognito Essentials (10,000 MAU free) round to zero. The only paid item is client-credentials token requests at USD 0.00225 each, with no free tier — ten tokens cost about USD 0.02. Free alternative: run the API locally with dotnet run and test tokens as in the module project's Auth:Mode=LocalTestIssuer.

cd infra/Harbourline.Lab42.Infra
cdk destroy --profile learn-sandbox --force

# Log groups are set to DESTROY; check that none survived
aws logs describe-log-groups --log-group-name-prefix /aws/lambda/hl-m04-l2 --profile learn-sandbox --region us-east-1
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
  --profile learn-sandbox --region us-east-1

Exercises

  • 🟢 Guided: deploy Lab 4.2 and reproduce the four results (401, 200, 403, 500 ProblemDetails). Find the Init Duration of the first invocation in CloudWatch Logs.
  • 🟡 Challenge: enable SnapStart: publish a version, add an alias live, point the integration at the alias, and compare Restore Duration with the previous Init Duration.
  • 🔴 Live problem: after moving the integration to payload format 1.0 "for compatibility with an old client", every request returns 500 and the logs show null reference errors in request marshalling. Explain and fix without breaking the old client.

Assignment

Add the Lab 4.2 solution to your portfolio repository with a README that shows the four curl results, a table of cold-start measurements (512 MB x86, 1024 MB ARM64, and SnapStart if you tried it), and a paragraph explaining why the app validates tokens even though API Gateway already does.

Solutions

Knowledge check

Interview questions

  • "Proxy or custom integration for a new .NET API?" — Proxy, almost always: the app owns the HTTP contract, errors are ProblemDetails, and the same code runs on Kestrel or Fargate. Custom integrations make sense for transforming legacy payloads at the edge.
  • "How do you avoid 502s with no detail?" — Handle exceptions inside ASP.NET Core, return ProblemDetails with trace and correlation IDs, customise REST gateway responses, and log $context.integrationErrorMessage.
  • "How would you cut .NET cold starts?" — Measure Init Duration; raise memory, use ARM64 and ReadyToRun; then SnapStart on an alias or Native AOT for small functions; provisioned concurrency only where latency SLAs justify the cost.
  • "What permissions does API Gateway need to call Lambda?" — A resource-based policy on the function granting lambda:InvokeFunction to apigateway.amazonaws.com, conditioned on the API's source ARN.
  • "Why validate the JWT in code if API Gateway already did?" — Defence in depth: a misconfigured route, a new integration path or a test invoke bypasses the authorizer, and only the app knows the ownership rule.

Certification practice

Completion checklist

  • I can explain proxy vs custom integrations and payload 1.0 vs 2.0
  • I deployed Lab 4.2 and saw 401, 200, 403 and a 500 ProblemDetails
  • I can predict the gateway status for crashes, timeouts and missing permissions
  • I measured a cold start in CloudWatch Logs
  • I ran cdk destroy and the tag check returned nothing

Key takeaways

  • Use proxy integrations and keep the HTTP contract (including ProblemDetails errors) in ASP.NET Core.
  • Match LambdaEventSource to the integration: RestApi = 1.0, HttpApi = 2.0.
  • Keep the Lambda timeout below the gateway timeout and make writes idempotent; the function keeps running after the client has been given up on.
  • SnapStart (.NET 8+, published versions) and Native AOT are the two main cold-start tools; choose one per function.
  • Scope-checked JWT authorizers at the edge plus token validation and ownership checks in code is the Harbourline default.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page