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).
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
LambdaEventSourcefor 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
dotnet10Lambda behind a Cognito JWT authorizer with scopes, test it with curl and PowerShell, and tear it down.
Prerequisites
- Amazon API Gateway: REST vs HTTP vs WebSocket
- Amazon Cognito user pools, app clients, resource servers and scopes (for the token part of the lab)
- Module 3: .NET on AWS — Lambda basics
- Tools: .NET 10 SDK, AWS CLI v2 (
learn-sandbox), Node.js + AWS CDK CLI,dotnet tool install -g Amazon.Lambda.Tools, Docker (only for Native AOT builds orsam local)
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 withstatusCode,headersandbody. 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 shape | Fixed: APIGatewayProxyRequest (payload 1.0) | Whatever your request mapping template produces |
| Response | Function returns statusCode, headers, body | Integration responses map output; status chosen by regex on errorMessage |
| Errors | Function decides status; a crash or malformed response gives 502 | Unmapped Lambda errors come back as 200 OK with the error JSON unless you add integration responses |
| Response streaming | Supported | Not supported |
| Use when | Almost 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.0 | 2.0 | |
|---|---|---|
| .NET event type | APIGatewayProxyRequest | APIGatewayHttpApiV2ProxyRequest |
| Repeated headers / query strings | multiValueHeaders, multiValueQueryStringParameters | Joined with commas in headers and queryStringParameters |
| Path | path, resource | rawPath, rawQueryString, routeKey |
| Cookies | Inside headers | Separate cookies array; response cookies become set-cookie headers |
| JWT claims | requestContext.authorizer.claims | requestContext.authorizer.jwt.claims and .scopes |
| Response | Must return statusCode etc. | May return plain JSON; API Gateway then assumes 200 and application/json |
| Custom domain mapping | path includes the API mapping | rawPath 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.
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 happens | REST API (proxy) | HTTP API (payload 2.0) |
|---|---|---|
| Your code returns 400/404/409 ProblemDetails | Passed through unchanged | Passed through unchanged |
An ASP.NET Core endpoint throws, UseExceptionHandler is on | 500 ProblemDetails from your app | Same |
| The handler itself crashes or returns a malformed response | 502 {"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 permission | 500 | {"message":"Internal Server Error"} |
| Non-proxy integration, error not mapped | 200 with the Lambda error JSON | Not 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.
| Option | What it does | Notes for .NET |
|---|---|---|
| More memory (1024–2048 MB) | More CPU during init | Often the cheapest fix; measure with the Init Duration log line |
| ARM64 (Graviton) | Lower price per GB-second | Build for linux-arm64 |
| ReadyToRun | Pre-compiles IL | Larger package, faster JIT |
| SnapStart | Snapshots the initialised environment when you publish a version | Supported 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 AOT | Compiles to a native binary | Runs 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 concurrency | Keeps environments warm | Steady 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-serverlessorsam build && sam deployforserverless.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 equivalent | What's different |
|---|---|---|
| Azure Functions HTTP trigger | Lambda behind API Gateway (proxy) or a Lambda function URL | The HTTP front door is a separate service with its own timeout, auth and pricing |
APIM set-backend-service + policies transforming payloads | REST API custom integration with VTL mapping templates | VTL instead of APIM policy expressions; HTTP APIs cannot transform bodies |
| ASP.NET Core on App Service | ASP.NET Core on Lambda via AddAWSLambdaHosting | Same 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 instances | Provisioned concurrency or SnapStart | SnapStart restores a snapshot instead of keeping instances running |
Easy Auth / APIM validate-jwt | API Gateway JWT/Cognito authorizer + JwtBearer in code | Validate 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
- Console → API Gateway → APIs → hl-m04-l2-accounts-api → Routes: each route shows JWT authorization and its scopes.
- 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 checksclient_idwhen the token has noaud). - Integrations: the Lambda integration shows Payload format version 2.0.
- Lambda → Functions → hl-m04-l2-accounts → Configuration → Permissions → Resource-based policy statements: one statement per route, each with a
SourceArncondition. - Lambda → Monitor → View CloudWatch logs: look for
Init Durationon 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 | jqPowerShell 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
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 },
});
}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
<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>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
AddAWSLambdaHosting(LambdaEventSource.HttpApi)— inside Lambda, registers a server that converts HTTP API payload 2.0 events intoHttpContext; on your laptop it does nothing, sodotnet runserves on Kestrel.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.Cognito:Issuer—https://cognito-idp.us-east-1.amazonaws.com/<poolId>; set by the CDK as the environment variableCognito__Issuer(double underscore = section separator).options.Authority = issuer— JwtBearer downloads the OIDC discovery document and the JWKS from the issuer and caches the signing keys.MapInboundClaims = false— keepssub,scope,client_id,token_usewith their JWT names instead of long WS-Federation claim URIs.ValidateAudience = false— Cognito access tokens have noaud; theclient_idallow-list inOnTokenValidatedreplaces the audience check.token_use != "access"— rejects Cognito ID tokens, which a careless client might send.AddAuthorizationBuilder().AddPolicy(...)— scope policies, the same names as the module project (accounts:read,statements:write).user.FindFirstValue("sub") == serviceClientId— a learning shortcut: in a client-credentials tokensubequals the client ID, so we pretend that client is customerCUS-00012345. Real code resolvessubthrough a customer directory.Where(a => a.CustomerId == customerId)— ownership is enforced in the query; customer IDs never come from the URL.Results.Accepted(...)withGuid.CreateVersion7()— returns202 Acceptedand aLocationheader for an asynchronous statement request./v1/diagnostics/fail— throws so you can see a 500 ProblemDetails instead of a gateway error. Never ship such an endpoint.HasScope— Cognito puts scopes in one space-separatedscopeclaim.decimal Balanceand ISO currency codes — money is neverdouble.- CDK:
HttpUserPoolAuthorizerbuilds a JWT authorizer with issuer = the pool and audience = the listed client IDs. - CDK:
AuthorizationScopeson each route — API Gateway returns 403 when none of the route's scopes is in the token. - CDK:
HttpLambdaIntegration— payload format 2.0 by default and onelambda:InvokeFunctionpermission per route, scoped by source ARN. - CDK:
Timeout = Duration.Seconds(25)— below the HTTP API's 30-second maximum, so the function stops before the gateway gives up. - CDK: the
CfnStageescape 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
subare 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.RestApiwith 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-permissionoutside 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
| Symptom | Likely cause | Fix |
|---|---|---|
| 401 with a fresh token | Wrong issuer Region/pool, or Bearer prefix missing in a custom header | Compare token iss with the authorizer issuer; send Authorization: Bearer <token> |
| 403 from API Gateway | Token lacks every scope listed on the route | Request the scope in the token call; check the client's allowed scopes |
| 401 from the app but not the gateway | client_id not in Cognito:AllowedClientIds, or token_use is id | Fix configuration; use an access token |
{"message":"Internal Server Error"} | Missing invoke permission or handler crash | Add $context.integrationErrorMessage to access logs; check Lambda logs |
invalid_client from the token endpoint | Wrong secret or client not enabled for client credentials | Re-read the secret; check AllowedOAuthFlows |
| First request slow (2–4 s) | Cold start | More 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-1Exercises
- 🟢 Guided: deploy Lab 4.2 and reproduce the four results (401, 200, 403, 500 ProblemDetails). Find the
Init Durationof the first invocation in CloudWatch Logs. - 🟡 Challenge: enable SnapStart: publish a version, add an alias
live, point the integration at the alias, and compareRestore Durationwith the previousInit 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
Run the CLI section in order. In CloudWatch → Log groups → /aws/lambda/hl-m04-l2-accounts, the first REPORT line includes Init Duration: ... ms; later lines do not, because the environment is reused. The 401 and 403 responses never invoke Lambda (no log lines appear), which also means you do not pay for them in Lambda.
In CDK: set SnapStart = SnapStartConf.ON_PUBLISHED_VERSIONS on the function, create fn.CurrentVersion, then new Alias(this, "Live", new AliasProps { AliasName = "live", Version = fn.CurrentVersion }), and pass the alias to HttpLambdaIntegration. SnapStart only applies to published versions, never $LATEST. Expect the Restore Duration to be well below the original Init Duration; remember that .NET SnapStart adds cache and restore charges.
Payload 1.0 sends APIGatewayProxyRequest while the app was built with LambdaEventSource.HttpApi, which expects 2.0. The fix is not to change the payload for clients: payload format is invisible to HTTP callers. Revert the integration to 2.0. If a 1.0 integration is truly required (for example to read the custom-domain API mapping from path), switch the app to LambdaEventSource.RestApi, which understands 1.0.
Knowledge check
Answer: 200 OK with the Lambda error JSON. Custom integrations need integration responses with selection patterns to map errors to 4xx/5xx. Proxy integrations would give 502 instead.
Answer: 2.0. Format 1.0 keeps them in multiValueQueryStringParameters.
Answer: The client receives an error at the HTTP API's 30-second maximum, while the function runs to completion and is billed. Lower the Lambda timeout, speed up the call, or make the operation asynchronous.
Answer: .NET 8 and later managed runtimes, on published versions and aliases only, not with provisioned concurrency, EFS or ephemeral storage above 512 MB.
Answer: Cognito access tokens carry client_id instead of aud. The app checks client_id against an allow-list and token_use == "access".
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:InvokeFunctiontoapigateway.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
A developer moves an ASP.NET Core minimal API to Lambda behind an HTTP API with payload format 2.0, using Amazon.Lambda.AspNetCoreServer.Hosting. Which registration is correct?
A. AddAWSLambdaHosting(LambdaEventSource.RestApi)
B. AddAWSLambdaHosting(LambdaEventSource.HttpApi)
C. AddAWSLambdaHosting(LambdaEventSource.ApplicationLoadBalancer)
D. No registration; Lambda detects ASP.NET Core automatically
Answer: B. HttpApi matches payload 2.0. A expects REST API payload 1.0. C is for ALB targets. D is wrong: without the hosting registration the app starts Kestrel and never processes Lambda events.
A team creates an HTTP API Lambda integration with the AWS CLI. Every request returns {"message":"Internal Server Error"}, and the function's logs show no invocations. What is the most likely cause?
A. The function's execution role lacks logs:PutLogEvents
B. The function lacks a resource-based policy allowing apigateway.amazonaws.com to invoke it
C. Payload format 2.0 is not supported for .NET
D. The JWT authorizer rejected the token
Answer: B. Integrations created outside the console need aws lambda add-permission. A would still invoke the function (the Invocations metric would rise even if logs were missing). C is false. D returns 401/403, not 500.
A batch job must read account lists through an HTTP API but must never request statements. Tokens come from Cognito with client credentials. Which design enforces this with the least custom code?
A. Give the job an API key and check it in the Lambda function
B. Allow only the accounts.read scope on the job's app client and require statements.write on the statement route's JWT authorizer
C. Use an IAM authorizer and share an access key with the job
D. Put the statement route in a different stage
Answer: B. The token cannot contain a scope the client is not allowed, and API Gateway returns 403 when the route's scope is missing. A: API keys are not authorization. C: long-lived shared keys violate least privilege. D: stages do not provide authorization.
A .NET 10 Lambda function behind API Gateway shows 3-second cold starts during morning peaks. The team wants the lowest effort change without paying for always-on capacity. What should they do first?
A. Enable provisioned concurrency for 24 hours a day B. Enable SnapStart, publish a version and route the integration to an alias C. Move to a REST API custom integration D. Raise the API Gateway integration timeout
Answer: B. SnapStart supports .NET 8+ managed runtimes and needs published versions/aliases; it charges for snapshot cache and restores rather than idle capacity. A works but is always-on cost. C and D do not change initialization time.
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 destroyand the tag check returned nothing
Key takeaways
- Use proxy integrations and keep the HTTP contract (including ProblemDetails errors) in ASP.NET Core.
- Match
LambdaEventSourceto 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
- Create AWS Lambda proxy integrations for HTTP APIs
- Handle Lambda errors in API Gateway
- Gateway response types
- Control access to HTTP APIs with JWT authorizers
- Troubleshooting HTTP API Lambda integrations
- Improving startup performance with Lambda SnapStart
- Compile .NET Lambda function code to a native runtime format
- .NET 10 runtime now available in AWS Lambda
- Amazon.Lambda.AspNetCoreServer.Hosting README
- Amazon.Lambda.Annotations README
- AWS Lambda pricing
- Related: DVA-C03 · Module 3: .NET on AWS
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.
Amazon Cognito user pools: app clients, resource servers and scopes
Create a Cognito user pool with a resource server, custom scopes and app clients, get real access tokens, and configure the Account Information API to accept only the right ones.
Container-backed APIs: ALB, NLB and VPC Link
Put an ASP.NET Core API running on ECS Fargate behind API Gateway without exposing it to the internet, using VPC links to private load balancers, and know when to skip API Gateway entirely.