IAM/SigV4 authorisation and mTLS for machine callers
Protect API Gateway APIs for machine-to-machine callers with IAM authorisation (SigV4), resource policies, private APIs and mutual TLS, and choose the right control for internal services and B2B partners.
Assumes: .NET 10 LTS · AWS SDK for .NET v4 · Amazon.CDK.Lib 2.277.0 · Terraform AWS provider v6 · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Turn on IAM authorisation (
AWS_IAM) for REST API methods and HTTP API routes, and write least-privilegeexecute-api:Invokepolicies down to the method and path. - Write API Gateway resource policies and predict the result of same-account and cross-account evaluation.
- Build a private REST API reachable only through an interface VPC endpoint, restricted with
aws:SourceVpce. - Configure mutual TLS on a Regional custom domain with a truststore in S3, disable the default
execute-apiendpoint, and call it from C# with a client certificate. - Choose between OAuth tokens, IAM/SigV4, mTLS and combinations for internal services, batch jobs and B2B partners.
Prerequisites
- Authentication fundamentals: OAuth 2.0, OIDC, JWT
- Lambda authorizers
- Module 5: Security — IAM policy evaluation (recommended)
- Module 2: Networking — VPC endpoints
- Tools: .NET 10 SDK (or Docker), AWS CLI v2 with the
learn-sandboxprofile, OpenSSL (optional)
Why this matters in banking
Most traffic in a bank is not customers. It is the payments engine asking the sanctions service for a decision, the reconciliation job reading balances at 02:00, the card processor posting authorisations, and partners such as a credit bureau exchanging data under contract. These callers have no human to type a password and no browser for a redirect. Give them a long-lived shared API key and you have a credential that gets copied into scripts, emailed during an incident and never rotated. Regulators and auditors expect strong, attributable machine identities: you must be able to say which system made a call, prove that its credential is short-lived or bound to a key it can't share, and cut it off quickly.
AWS gives you two such identities out of the box: IAM principals (roles that sign requests with SigV4) for anything running in AWS, and X.509 client certificates (mTLS) for partners outside AWS.
The idea in plain language
IAM authorisation makes API Gateway behave like any AWS service. The caller signs each request with Signature Version 4 using temporary credentials from its IAM role (Lambda execution role, ECS task role, EC2 instance profile). API Gateway checks the signature, works out which role signed it, and evaluates IAM policies for the action execute-api:Invoke on the method's ARN. No tokens to issue, no secrets to store: credentials rotate automatically, every call is attributable to a role, and CloudTrail-style ARNs appear in your access logs.
A resource policy is an IAM policy attached to the API itself. It says who may call, from where (account, VPC endpoint, IP range). It is how you allow another AWS account, or restrict a private API to specific VPC endpoints.
A private API has no public endpoint at all. It is reachable only through an interface VPC endpoint for execute-api (AWS PrivateLink) from inside a VPC, or from on-premises over Direct Connect or VPN into that VPC.
Mutual TLS (mTLS) adds a second certificate to the TLS handshake. Normally only the server proves its identity with a certificate. With mTLS the client must also present a certificate issued by a CA you trust, and the handshake fails before any HTTP request is processed if it can't.
Analogy: IAM/SigV4 is the staff badge with a photo that every door reader checks against the HR system — it only works for people on the payroll (principals in AWS). mTLS is the contractor's company pass issued by an agency you have a contract with: the door checks the agency's stamp, not your HR system. A private API is a door that only exists inside the building.
What problem the AWS service solves
| Control | Proves | Works for | Where enforced | Limitations |
|---|---|---|---|---|
IAM (AWS_IAM) | Which IAM principal signed the request | Callers with AWS credentials | API Gateway, before integration | Callers need AWS credentials; partners outside AWS would need IAM users (avoid) or Roles Anywhere |
| Resource policy | Request comes from an allowed account, VPC endpoint, VPC or IP | REST APIs only | API Gateway | Max 8,192 characters by default; not available on HTTP APIs |
| Private API | Network path is through your interface endpoint | REST APIs only | Network + resource policy | Needs VPC endpoint (hourly cost); no mTLS on private APIs |
| mTLS | Client holds a private key for a certificate your CA chain trusts | Any client, inside or outside AWS | TLS handshake on a custom domain | Regional custom domain needed; API Gateway does not check revocation |
Key facts, verified against the API Gateway documentation:
- mTLS for REST APIs requires a Regional custom domain with the
TLS_1_2security policy, a server certificate in ACM, and a truststore (PEM bundle) in S3. The truststore can hold up to 1,000 certificates, 1 MB total, with chains up to four certificates long. - Clients can still reach the API through the default
https://{api-id}.execute-api.{region}.amazonaws.comendpoint unless you disable the default endpoint. - API Gateway returns 403 when the client certificate is untrusted, expired or uses an unsupported algorithm, and does not check revocation — do that in a Lambda authorizer if you need it.
- Mutual TLS isn't supported for private APIs. Inside a VPC you use IAM and resource policies; mTLS is for public (Regional) endpoints.
- If you use a certificate imported into ACM or from AWS Private CA as the server certificate, API Gateway also needs an ACM-issued ownership verification certificate for the domain.
- HTTP APIs support IAM authorisation on routes and mTLS on custom domains, but not resource policies or private endpoints.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Managed identity + Entra ID token to call an API | IAM role + SigV4-signed request with AWS_IAM auth | No token endpoint; the signature is the credential, per request |
APIM validate-azure-ad-token for daemon apps | AWS_IAM method authorisation, or Cognito client credentials | IAM is the native choice for AWS-to-AWS calls |
| APIM client certificate authentication | API Gateway mTLS on a Regional custom domain | Truststore lives in S3; revocation is your job |
| App Service "Access restrictions" / Private Endpoint | Resource policy + private REST API + interface VPC endpoint | Private APIs are a separate endpoint type, not a toggle |
| APIM in internal VNet mode | Private REST API | One VPC endpoint can serve many private APIs |
| Azure RBAC role assignment on an API | IAM identity policy with execute-api:Invoke and a method ARN | ARNs go down to stage, verb and path |
Architecture
Security boundary view. For the private API, three independent checks must all pass: the network path (the endpoint), the resource policy (aws:SourceVpce), and the caller's IAM permissions. For the partner API, the TLS handshake proves possession of a private key, and the Lambda authorizer maps the certificate's subject to a partner and checks revocation, so a stolen-and-revoked certificate is refused even though API Gateway alone would accept it.
Step-by-step implementation
Turn on IAM authorisation for a method
On a REST API, set the method's authorisation type to AWS_IAM. On an HTTP API, set the route's authoriser to IAM. Unsigned requests now get 403 Missing Authentication Token-style responses, and signed requests from principals without permission get 403 User: arn:aws:sts::... is not authorized to perform: execute-api:Invoke.
Write the identity policy
The resource ARN format is:
arn:aws:execute-api:{region}:{account-id}:{api-id}/{stage}/{HTTP-VERB}/{resource-path}Least privilege for the reconciliation job — only GET, only the learn stage, only the balances path:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadBalancesOnly",
"Effect": "Allow",
"Action": "execute-api:Invoke",
"Resource": "arn:aws:execute-api:us-east-1:111122223333:a1b2c3d4e5/learn/GET/internal/accounts/*/balance"
}
]
}* in the path matches any characters, including slashes, so GET/internal/* is broad. Prefer explicit paths for money-moving operations.
Add a resource policy and understand evaluation
A resource policy on a REST API combines with identity policies:
| Caller | Identity policy | Resource policy | Result |
|---|---|---|---|
Same account, AWS_IAM auth | Allow | none / silent | Allow |
Same account, AWS_IAM auth | silent | Allow | Allow |
| Same account | any | explicit Deny | Deny |
Other account, AWS_IAM auth | Allow | Allow for that account/role | Allow |
| Other account | Allow | silent | Deny — cross-account needs both |
Explicit deny always wins. A resource policy is also how you restrict by network: aws:SourceVpce, aws:SourceVpc (private APIs) or aws:SourceIp (public APIs). After changing a resource policy on a REST API, redeploy the API for it to take effect.
Make the API private
- Create an interface VPC endpoint for
com.amazonaws.us-east-1.execute-apiin private subnets, with a security group that allows 443 from your workloads. - Create the REST API with endpoint type
PRIVATE. - Attach a resource policy that allows
execute-api:Invokeonly whenaws:SourceVpceequals your endpoint ID (and denies otherwise). A private API with no resource policy can't be invoked. - Invoke it with private DNS turned on (
https://{api-id}.execute-api.us-east-1.amazonaws.com/learn/...resolves to the endpoint), or with the endpoint-specific hostname and anx-apigw-api-idheader, or by associating the endpoint with the API to get a Route 53 alias.
Caution: with private DNS turned on for the execute-api endpoint, workloads in that VPC can no longer reach public API Gateway APIs through their default execute-api hostnames. Plan this before enabling it in a shared VPC.
Configure mutual TLS for a partner domain
- Build the truststore: the issuing CA and every intermediate up to the root, concatenated in one
.pemfile. Upload it to a versioned S3 bucket with Block Public Access on. - Request or import the server certificate for
partner-api.harbourline.examplein ACM in the same Region as the API. - Create a Regional custom domain with security policy
TLS_1_2and--mutual-tls-authentication truststoreUri=s3://bucket/truststore.pem. - Map the API stage to the domain (base path mapping) and create the DNS record.
- Disable the default
execute-apiendpoint on the API so nobody can bypass mTLS. - Optionally add a Lambda authorizer that reads the certificate details from the request context (subject, issuer, serial number, validity) and checks a revocation list or an allow-list of serial numbers.
When you rotate the truststore, upload a new object version and update the domain's truststoreVersion. API Gateway reports certificate warnings only at update time; it doesn't notify you when a CA in the truststore later expires — put that in your certificate inventory and alarms.
Choose per caller
| Caller | Recommended control |
|---|---|
| Lambda, ECS, EC2 in your AWS organisation | AWS_IAM + resource policy (aws:PrincipalOrgID), private API if no internet path is needed |
| On-premises system over Direct Connect | Private API via the VPC endpoint + IAM (IAM Roles Anywhere for credentials) or a Lambda authorizer |
| External partner over the internet | mTLS on a Regional custom domain plus an OAuth client-credentials token or Lambda authorizer for per-partner authorisation |
| Customers in apps | OAuth 2.0 + Cognito (the Cognito lesson) — never IAM users |
AWS Console instructions
- IAM auth: Console → API Gateway → APIs → (REST API) → Resources → select method → Method request → Edit → Authorization: AWS IAM → Save → Deploy API.
- Resource policy: API → Resource policy → Edit → paste JSON → Save → Deploy API.
- Private API: Console → VPC → Endpoints → Create endpoint → AWS services →
com.amazonaws.us-east-1.execute-api→ choose VPC, private subnets, security group → Create. Then API Gateway → Create API → REST API → API endpoint type Private → add the VPC endpoint ID. - mTLS: API Gateway → Custom domain names → Create → Regional, TLS 1.2 → turn on Mutual TLS authentication → Truststore URI
s3://…→ choose ACM certificate → Create. Then API mappings → Add. Finally API → API settings → Default endpoint → Inactive.
AWS CLI
# 1. Require IAM auth on GET /internal/accounts/{accountId}/balance (REST API).
aws apigateway update-method --rest-api-id a1b2c3d4e5 --resource-id abc123 --http-method GET \
--patch-operations op=replace,path=/authorizationType,value=AWS_IAM \
--profile learn-sandbox --region us-east-1
# 2. Attach a resource policy from policy.json, then redeploy.
# jq builds the patch document so the policy JSON is escaped correctly.
jq -n --arg p "$(jq -c . policy.json)" '[{op:"replace",path:"/policy",value:$p}]' > patch.json
aws apigateway update-rest-api --rest-api-id a1b2c3d4e5 --patch-operations file://patch.json \
--profile learn-sandbox --region us-east-1
aws apigateway create-deployment --rest-api-id a1b2c3d4e5 --stage-name learn \
--profile learn-sandbox --region us-east-1
# 3. Call an IAM-protected API from the CLI machine: curl can sign SigV4 itself (curl 7.75+).
# Credentials come from the SSO profile via 'aws configure export-credentials'.
# Whether curl includes the session-token header in the signature depends on its version ⚠ VERIFY.
eval "$(aws configure export-credentials --profile learn-sandbox --format env)"
curl --aws-sigv4 "aws:amz:us-east-1:execute-api" \
--user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
-H "x-amz-security-token: $AWS_SESSION_TOKEN" \
https://a1b2c3d4e5.execute-api.us-east-1.amazonaws.com/learn/internal/accounts/ACC-0000012345/balance
# 4. mTLS custom domain (needs an ACM certificate for the domain and the truststore in S3).
aws s3 cp truststore.pem s3://hl-m04-truststore-111122223333/truststore.pem --profile learn-sandbox
aws apigateway create-domain-name --domain-name partner-api.harbourline.example \
--regional-certificate-arn arn:aws:acm:us-east-1:111122223333:certificate/EXAMPLE \
--endpoint-configuration types=REGIONAL --security-policy TLS_1_2 \
--mutual-tls-authentication truststoreUri=s3://hl-m04-truststore-111122223333/truststore.pem \
--profile learn-sandbox --region us-east-1
# 5. Close the bypass: disable the default execute-api endpoint, then redeploy.
aws apigateway update-rest-api --rest-api-id a1b2c3d4e5 \
--patch-operations op=replace,path=/disableExecuteApiEndpoint,value='True' \
--profile learn-sandbox --region us-east-1
# 6. Test from the partner side: with and without the client certificate.
curl -v --cert partner-client.pem --key partner-client.key https://partner-api.harbourline.example/partner/health
curl -v https://partner-api.harbourline.example/partner/health # handshake failsOn Windows PowerShell, step 3 is easier with the C# handler in this module's service-to-service lesson, and step 6 with the C# client below.
Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.APIGateway;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.Lambda;
using Constructs;
namespace Harbourline.Internal.Infra;
public sealed class InternalApiStack : Stack
{
public InternalApiStack(Construct scope, string id, IStackProps props, IVpc vpc, IFunction balances, IRole reconciliationRole)
: base(scope, id, props)
{
// Interface endpoint for API Gateway in the private subnets (billed per AZ-hour + per GB).
var endpoint = vpc.AddInterfaceEndpoint("ExecuteApiEndpoint", new InterfaceVpcEndpointOptions
{
Service = InterfaceVpcEndpointAwsService.APIGATEWAY,
PrivateDnsEnabled = true,
Subnets = new SubnetSelection { SubnetType = SubnetType.PRIVATE_WITH_EGRESS },
});
var api = new RestApi(this, "InternalApi", new RestApiProps
{
RestApiName = "hl-m04-internal",
EndpointConfiguration = new EndpointConfiguration { Types = [EndpointType.PRIVATE], VpcEndpoints = [endpoint] },
DeployOptions = new StageOptions { StageName = "learn" },
Policy = new PolicyDocument(new PolicyDocumentProps
{
Statements =
[
new PolicyStatement(new PolicyStatementProps
{
Effect = Effect.DENY,
Principals = [new AnyPrincipal()],
Actions = ["execute-api:Invoke"],
Resources = ["execute-api:/*"],
Conditions = new Dictionary<string, object>
{
["StringNotEquals"] = new Dictionary<string, object> { ["aws:SourceVpce"] = endpoint.VpcEndpointId },
},
}),
new PolicyStatement(new PolicyStatementProps
{
Effect = Effect.ALLOW,
Principals = [new ArnPrincipal(reconciliationRole.RoleArn)],
Actions = ["execute-api:Invoke"],
Resources = ["execute-api:/learn/GET/internal/accounts/*/balance"],
}),
],
}),
});
var balance = api.Root.AddResource("internal").AddResource("accounts")
.AddResource("{accountId}").AddResource("balance");
balance.AddMethod("GET", new LambdaIntegration(balances), new MethodOptions
{
AuthorizationType = AuthorizationType.IAM,
});
// The caller's identity policy: same method ARN, least privilege.
reconciliationRole.AddToPrincipalPolicy(new PolicyStatement(new PolicyStatementProps
{
Actions = ["execute-api:Invoke"],
Resources = [api.ArnForExecuteApi("GET", "/internal/accounts/*/balance", "learn")],
}));
}
}For the partner domain with mTLS:
var truststoreBucket = new Amazon.CDK.AWS.S3.Bucket(this, "Truststore", new Amazon.CDK.AWS.S3.BucketProps
{
Versioned = true,
BlockPublicAccess = Amazon.CDK.AWS.S3.BlockPublicAccess.BLOCK_ALL,
Encryption = Amazon.CDK.AWS.S3.BucketEncryption.S3_MANAGED,
EnforceSSL = true,
});
var domain = new DomainName(this, "PartnerDomain", new DomainNameProps
{
DomainName = "partner-api.harbourline.example",
Certificate = certificate, // ACM certificate in the same Region
EndpointType = EndpointType.REGIONAL,
SecurityPolicy = SecurityPolicy.TLS_1_2,
Mtls = new MTLSConfig { Bucket = truststoreBucket, Key = "truststore.pem" },
});
domain.AddBasePathMapping(partnerApi, new BasePathMappingOptions { BasePath = "partner" });
// On the RestApi itself: DisableExecuteApiEndpoint = trueComplete code
Three small, runnable pieces. Together they let you rehearse mTLS end to end locally before you spend anything on a custom domain.
1. Create a private test CA, a partner client certificate and the truststore (console app, no packages needed):
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
var outDir = Directory.CreateDirectory(args.Length > 0 ? args[0] : "mtls-out").FullName;
// Root CA: ECDSA P-256 (supported by API Gateway truststores), 2 years, CA basic constraint.
using var caKey = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var caRequest = new CertificateRequest("CN=Harbourline Partner Test CA, O=Harbourline Bank (fictional)", caKey, HashAlgorithmName.SHA256);
caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, true, 0, true));
caRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true));
caRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(caRequest.PublicKey, false));
using var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddYears(2));
// Client certificate for one partner: short-lived (90 days), clientAuth only.
using var clientKey = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var clientRequest = new CertificateRequest("CN=sentinel-credit-bureau, O=Sentinel Credit Bureau (fictional)", clientKey, HashAlgorithmName.SHA256);
clientRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
clientRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));
clientRequest.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension([new Oid("1.3.6.1.5.5.7.3.2")], true)); // clientAuth
var serial = RandomNumberGenerator.GetBytes(16);
using var clientPublic = clientRequest.Create(ca, DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddDays(90), serial);
using var client = clientPublic.CopyWithPrivateKey(clientKey);
// truststore.pem is what goes to S3. The client key never leaves the partner.
File.WriteAllText(Path.Combine(outDir, "truststore.pem"), ca.ExportCertificatePem());
File.WriteAllText(Path.Combine(outDir, "partner-client.pem"), client.ExportCertificatePem());
File.WriteAllText(Path.Combine(outDir, "partner-client.key"), clientKey.ExportPkcs8PrivateKeyPem());
Console.WriteLine($"CA: {ca.Subject} thumbprint {ca.Thumbprint}");
Console.WriteLine($"Client: {client.Subject} serial {client.SerialNumber} expires {client.NotAfter:u}");
Console.WriteLine($"Files written to {outDir}");2. The partner's C# client: present the certificate on every TLS handshake.
using System.Security.Cryptography.X509Certificates;
namespace Harbourline.Partners;
public static class PartnerClientFactory
{
/// <summary>HttpClient that presents a client certificate (mTLS) and still validates the server normally.</summary>
public static HttpClient Create(Uri baseAddress, string certPemPath, string keyPemPath)
{
// Re-export as PKCS#12: on Windows, SChannel needs a persisted key for client auth.
using var pem = X509Certificate2.CreateFromPemFile(certPemPath, keyPemPath);
var cert = X509CertificateLoader.LoadPkcs12(pem.Export(X509ContentType.Pkcs12), password: null);
var handler = new SocketsHttpHandler
{
SslOptions = { ClientCertificates = new X509CertificateCollection { cert } },
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
};
return new HttpClient(handler) { BaseAddress = baseAddress, Timeout = TimeSpan.FromSeconds(10) };
}
}3. A local mTLS server in ASP.NET Core that behaves like the API Gateway custom domain (requires a trusted client certificate, checks the chain against the same truststore), so you can test the client without AWS:
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Server.Kestrel.Https;
var dir = args.Length > 0 ? args[0] : "mtls-out";
var trustedCa = X509Certificate2.CreateFromPem(File.ReadAllText(Path.Combine(dir, "truststore.pem")));
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(k => k.ListenLocalhost(5443, listen => listen.UseHttps(https =>
{
https.ClientCertificateMode = ClientCertificateMode.RequireCertificate; // no cert, no handshake
https.ClientCertificateValidation = (cert, _, _) =>
{
using var chain = new X509Chain();
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; // trust only our truststore
chain.ChainPolicy.CustomTrustStore.Add(trustedCa);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; // like API Gateway: no revocation check
chain.ChainPolicy.ApplicationPolicy.Add(new System.Security.Cryptography.Oid("1.3.6.1.5.5.7.3.2"));
return chain.Build(cert);
};
})));
var app = builder.Build();
app.MapGet("/partner/health", (HttpContext ctx) =>
{
var cert = ctx.Connection.ClientCertificate!;
// API Gateway passes the same facts in the request context (subject, issuer, serial, validity).
return Results.Ok(new { partner = cert.GetNameInfo(X509NameType.SimpleName, false), serial = cert.SerialNumber });
});
app.Run();Run it with the ASP.NET Core development certificate as the server certificate (dotnet dev-certs https --trust once), then:
using var http = Harbourline.Partners.PartnerClientFactory.Create(
new Uri("https://localhost:5443/"), "mtls-out/partner-client.pem", "mtls-out/partner-client.key");
Console.WriteLine(await http.GetStringAsync("partner/health"));
// {"partner":"sentinel-credit-bureau","serial":"…"}Removing the certificate from the client makes the handshake fail with an HttpRequestException whose inner exception is an AuthenticationException — the same behaviour as API Gateway's mTLS domain.
Reading the certificate behind API Gateway. In a REST API Lambda proxy integration, the client certificate appears in requestContext.identity.clientCert (clientCertPem, subjectDN, issuerDN, serialNumber, validity). With Amazon.Lambda.AspNetCoreServer, the original event is in HttpContext.Items["LambdaRequestObject"]:
using Amazon.Lambda.APIGatewayEvents;
namespace Harbourline.Partners;
public static class PartnerIdentity
{
private static readonly Dictionary<string, string> PartnersBySerial = new(StringComparer.OrdinalIgnoreCase)
{
["0A1B2C3D4E5F60718293A4B5C6D7E8F9"] = "sentinel-credit-bureau", // fictional
};
/// <summary>Maps the mTLS certificate to a partner; null if unknown (treat as 403).</summary>
public static string? Resolve(HttpContext http)
{
if (http.Items["LambdaRequestObject"] is not APIGatewayProxyRequest request) return null;
var cert = request.RequestContext?.Identity?.ClientCert;
if (cert?.SerialNumber is not { } serial) return null;
return PartnersBySerial.GetValueOrDefault(serial.Replace(":", "", StringComparison.Ordinal));
}
}The exact property names come from the Amazon.Lambda.APIGatewayEvents package (ProxyRequestClientCert) ⚠ VERIFY against the version you install.
Code explained line by line
ECDsa.Create(ECCurve.NamedCurves.nistP256)— ECDSA-256 is one of the key types API Gateway accepts in truststores (alongside RSA-2048 or stronger and ECDSA-384), with SHA-256 or stronger signatures.X509BasicConstraintsExtension(true, true, 0, true)— marks the root as a CA that may sign end-entity certificates only (path length 0).X509EnhancedKeyUsageExtension(... "1.3.6.1.5.5.7.3.2")—clientAuth. A server certificate stolen from elsewhere can't be used as a client certificate if you check this.clientRequest.Create(ca, ..., serial)— the CA signs the partner certificate. A random 128-bit serial lets you identify and revoke it.ExportCertificatePem()for the CA becomestruststore.pem. For a real chain, append the intermediate(s) and the root to the same file.X509Certificate2.CreateFromPemFile+LoadPkcs12— loads the certificate and key; the PKCS#12 round trip avoids an ephemeral-key problem with SChannel on Windows.SslOptions.ClientCertificates— the handler offers the certificate during the TLS handshake. Server certificate validation stays on.ClientCertificateMode.RequireCertificateandCustomRootTrust— the local server mirrors API Gateway: only certificates chaining to the truststore pass.RevocationMode.NoCheck— deliberately mirrors API Gateway, which doesn't check revocation; thePartnerIdentitymap (or a Lambda authorizer with a deny-list) is where revocation lives.PartnerIdentity.Resolve— authentication (TLS) proved possession of a key; this maps it to a business identity and gives you a place to refuse unknown or revoked serials.
Security considerations
⚠ Learning shortcut — not for production
The test CA's private key sits on your laptop and you issue certificates from a console app. In production the CA lives in AWS Private CA (or the partner's CA under contract), keys for client certificates are generated by the partner and never sent to you (they send a CSR), and the CA key is protected by an HSM. Also, IAM examples here use learn stage ARNs with wildcards for readability; production policies should name each path explicitly.
- Close the bypass. With mTLS or a custom domain, disable the default
execute-apiendpoint; otherwise attackers simply skip your domain. - Revocation is yours. Keep certificate lifetimes short (90 days or less) and maintain a deny-list of serials in a Lambda authorizer.
- Don't stop at mTLS. mTLS proves the client holds a key; it doesn't say what that partner may do. Combine it with an OAuth client-credentials token or a Lambda authorizer for per-partner authorisation and throttling.
- Least privilege on
execute-api:Invoke. Separate read and write paths; never grantexecute-api:*(that includesManageConnectionsandInvalidateCache). - Organisation guard rails. Add
aws:PrincipalOrgIDto resource policies and use service control policies so a role in a non-Harbourline account can't be granted access by mistake. - Logs. Include
$context.identity.userArnor$context.identity.caller(IAM) and the client certificate serial (mTLS) in access logs, so every call is attributable. Treat certificates and ARNs as operational data, not secrets.
Banking use case
Harbourline's Sentinel Credit Bureau integration: the bureau calls partner-api.harbourline.example with a client certificate issued by Harbourline's partner CA (in AWS Private CA). A Lambda authorizer maps the serial to partner=sentinel, checks a revocation list in DynamoDB, and attaches the partner ID to the request; the API throttles per partner with a usage plan (next lesson). Internally, the reconciliation job on Fargate reads balances from a private REST API through the VPC endpoint using its task role — no secrets anywhere, every call attributable to arn:aws:sts::111122223333:assumed-role/hl-reconciliation-task/....
Common mistakes
- Forgetting to redeploy after changing a REST API resource policy → old policy still applies →
create-deploymentafter every policy change. - Leaving the default endpoint on with mTLS → mTLS bypassed → disable it.
- Truststore with only the root when certificates are issued by an intermediate → handshake fails → include the full chain.
- Signing with the wrong service name (
apigatewayinstead ofexecute-api) →Credential should be scoped to correct service→ the signing name for invoking APIs isexecute-api. - Cross-account call allowed only in the caller's account → 403 → the API's resource policy must also allow the caller.
- Enabling private DNS on the
execute-apiendpoint in a shared VPC → other teams' calls to public APIs break → coordinate or use Route 53 aliases instead.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
403 Missing Authentication Token | Wrong path or stage, or unsigned request to an AWS_IAM method | Check URL and stage; sign the request |
403 ... is not authorized to perform: execute-api:Invoke on resource ... | Identity policy ARN doesn't match (verb, stage or path) | Compare the ARN in the message with the policy |
403 User: anonymous is not authorized on a private API | Resource policy missing or request not via the endpoint | Add the aws:SourceVpce allow; check DNS resolves to the endpoint ENIs |
403 The request signature we calculated does not match | Proxy changed a header, or path not double-encoded | See the SigV4 lesson troubleshooting |
| TLS handshake failure from a partner | Client cert not chained to truststore, expired or unsupported algorithm | openssl verify -CAfile truststore.pem partner-client.pem |
| Domain shows certificate warnings after update | A certificate in the truststore is invalid | Decode with openssl x509 -text, fix, upload a new version |
| Timeout calling a private API from a Lambda | Lambda not in the VPC, or endpoint security group blocks 443 | Put the function in the VPC; allow 443 from its security group |
Cost and cleanup
Labelled credits because the private-API and mTLS parts create billable resources:
- Interface VPC endpoint: charged per endpoint per AZ-hour plus per GB processed (about USD 0.01 per AZ-hour in us-east-1 ⚠ VERIFY on the PrivateLink pricing page). Two AZs for one hour ≈ USD 0.02.
- API Gateway REST API: per million requests; lab traffic is pennies or free-tier.
- Custom domain with mTLS: no extra API Gateway charge for the domain itself ⚠ VERIFY; you need a domain you control and an ACM certificate (public ACM certificates are free).
Free alternative: run the three C# programs above locally — the CA generator, the Kestrel mTLS server and the partner client — and use the IAM policy simulator for execute-api:Invoke ARNs. No AWS resources needed.
Teardown if you deployed:
aws apigateway delete-base-path-mapping --domain-name partner-api.harbourline.example --base-path partner --profile learn-sandbox
aws apigateway delete-domain-name --domain-name partner-api.harbourline.example --profile learn-sandbox
aws apigateway delete-rest-api --rest-api-id a1b2c3d4e5 --profile learn-sandbox
aws ec2 delete-vpc-endpoints --vpc-endpoint-ids vpce-0123456789abcdef0 --profile learn-sandbox
aws s3 rm s3://hl-m04-truststore-111122223333 --recursive --profile learn-sandbox
# Confirm nothing tagged for the lab remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
--query "ResourceTagMappingList[].ResourceARN" --profile learn-sandbox --region us-east-1Exercises
- 🟢 Guided: Run the CA generator, the local mTLS server and the partner client. Show one successful call and one failing call (no certificate). Then issue a second client certificate from a different CA and show that it also fails.
- 🟡 Challenge: Write an IAM identity policy that allows the reconciliation role to call
GET /internal/accounts/*/balanceandGET /internal/accounts/*/transactionson stagelearnonly, and denies everything on stageprod. Validate it with the IAM policy simulator. - 🔴 Live problem: A partner reports "our calls started failing with a TLS error this morning; nothing changed on our side". Your truststore was last updated six months ago. List what you check, in order, and what you change.
Assignment
Produce a machine-identity decision record for Harbourline: for each caller type (internal AWS workload, on-premises system, external partner, customer app), the chosen control(s), credential lifetime, revocation method, how calls are attributed in logs, and the cost. Include the IAM policy and resource policy JSON for one internal API.
Solutions
The call with the certificate returns the partner name and serial. Without a certificate, Kestrel aborts the handshake and the client throws HttpRequestException (inner AuthenticationException or IOException). With a certificate from another CA, chain.Build fails because CustomRootTrust only trusts your truststore. This is exactly how an API Gateway mTLS domain behaves: trust is decided by the truststore, not by Windows' certificate store.
Two Allow statements (or one with two resources) for arn:aws:execute-api:us-east-1:111122223333:a1b2c3d4e5/learn/GET/internal/accounts/*/balance and .../transactions, plus a Deny statement for arn:aws:execute-api:us-east-1:111122223333:a1b2c3d4e5/prod/*. The explicit Deny protects against a later broad Allow added by someone else. The simulator should show "allowed" for the two learn ARNs and "explicitly denied" for any prod ARN.
- Check whether the partner's client certificate expired (most common) — ask for the serial and
NotAfter, or look at access logs for the last successful call. 2) Check whether an intermediate CA certificate in your truststore expired — API Gateway doesn't warn about that after upload. 3) Check whether someone updated the domain's truststore version or the S3 object. 4) Check whether the partner's library now sends a different chain or algorithm. Fix by issuing a new client certificate or updating the truststore with the renewed intermediate (new S3 version,update-domain-namewith the newtruststoreVersion). Prevent recurrence with an inventory of certificate expiry dates and alarms 30 days ahead.
Knowledge check
Answer: Cross-account access needs an Allow in both places: the caller's identity policy and the API's resource policy in account B. Add a resource policy statement allowing the role ARN (or account A with conditions), then redeploy.
Answer: No. API Gateway doesn't support mutual TLS for private APIs. Use IAM authorisation and resource policies with aws:SourceVpce inside the VPC, or terminate mTLS elsewhere (for example on an ALB, which supports mTLS) in front of a private integration.
Answer: No. It checks syntax, integrity, validity period and chain. Revocation checks (CRL/OCSP or a deny-list) belong in a Lambda authorizer.
Answer: execute-api. (apigateway is the management API used to create and change APIs.)
Interview questions
- "How do you secure service-to-service calls on AWS without secrets?" IAM roles for each workload, SigV4-signed requests,
AWS_IAMauthorisation on the API, resource policies restricting accounts/organisation and VPC endpoints, private APIs where no internet path is needed. Credentials are temporary and rotate automatically. - "When would you use mTLS instead of OAuth client credentials?" When the caller is outside AWS and you need a credential bound to a private key that can't be replayed by copying a string; often both: mTLS for transport-level identity, OAuth for scopes and per-partner policy. FAPI-style Open Banking uses certificate-bound tokens to tie the two together.
- "What are the gaps in API Gateway's mTLS?" No revocation checking, no mTLS on private APIs, default endpoint must be disabled manually, truststore expiry isn't monitored for you.
- "Explain resource policy evaluation for API Gateway." Explicit deny wins; same-account calls need an allow in either the identity policy or the resource policy; cross-account calls need both.
Certification practice
A bank exposes a REST API to a partner over the internet. Requirements: the partner must present an X.509 certificate issued by the bank's private CA, and nobody may reach the API without it. Which combination meets the requirements? (Choose two.)
A. Enable mutual TLS on a Regional custom domain with the CA chain as the truststore in S3. B. Disable the API's default execute-api endpoint. C. Create an API key for the partner and require it on all methods. D. Make the API private and share the VPC endpoint with the partner. E. Enable AWS WAF with the managed common rule set.
Answer: A and B. A enforces certificates on the custom domain; B removes the bypass. C isn't authentication. D: private APIs don't support mTLS, and partners outside AWS can't use your endpoint. E filters attacks but doesn't require certificates.
A .NET service on ECS calls a REST API method configured with AWS_IAM authorisation and gets 403 Missing Authentication Token. The task role has an execute-api:Invoke allow for the method. What is the most likely cause?
A. The request isn't signed with SigV4.
B. The API needs a Cognito authorizer.
C. The usage plan quota is exhausted.
D. The task role needs apigateway:GET.
Answer: A. Unsigned requests to AWS_IAM methods (or wrong paths) produce this message. B is a different auth type. C returns 429. D is a management permission, not invoke.
An internal API must be reachable only from workloads in two VPCs and never from the internet, with the least operational effort. What should the architect do?
A. Regional REST API with a resource policy restricting aws:SourceIp to the VPC CIDRs.
B. Private REST API, interface VPC endpoints for execute-api in each VPC, and a resource policy allowing only those endpoint IDs.
C. Edge-optimized API with AWS WAF IP sets.
D. HTTP API with a VPC Link.
Answer: B. Private APIs have no public endpoint, and aws:SourceVpce restricts to the endpoints. A: private IPs don't appear as source IPs on a public endpoint, and it stays internet-facing. C is public. D: a VPC Link connects API Gateway to private backends; it doesn't make the API private.
Completion checklist
- I can write an
execute-api:InvokeARN for a specific stage, verb and path - I can explain same-account vs cross-account resource policy evaluation
- I generated a test CA and client certificate and tested mTLS locally
- I know the three gaps of API Gateway mTLS (revocation, private APIs, default endpoint)
- I deleted any VPC endpoint, domain and API I created, and the tag query returns nothing
Key takeaways
- For callers in AWS, IAM + SigV4 is the default machine identity: no secrets, automatic rotation, full attribution.
- Resource policies add who/where conditions; cross-account access needs both sides to allow.
- Private REST APIs remove the public endpoint; combine with
aws:SourceVpceand IAM. - mTLS suits partners outside AWS, on Regional custom domains only; disable the default endpoint and handle revocation yourself.
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.
Lambda authorizers: custom authorisation in front of your API
Write, test and deploy a C# Lambda authorizer that validates JWTs with cached JWKS keys, returns cache-safe IAM policies and passes the customer ID to the backend.
Request validation, models, versioning and CORS
Reject bad input in layers (API Gateway models and validators, ASP.NET Core 10 validation, mass-assignment defences), version APIs on API Gateway, and finally understand CORS preflight on REST APIs, HTTP APIs and ASP.NET Core.