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

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.

advanced⏱ 1 h 30 min🟡 Low costSCS-C03DVA-C03SAA-C03

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-privilege execute-api:Invoke policies 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-api endpoint, 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

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

ControlProvesWorks forWhere enforcedLimitations
IAM (AWS_IAM)Which IAM principal signed the requestCallers with AWS credentialsAPI Gateway, before integrationCallers need AWS credentials; partners outside AWS would need IAM users (avoid) or Roles Anywhere
Resource policyRequest comes from an allowed account, VPC endpoint, VPC or IPREST APIs onlyAPI GatewayMax 8,192 characters by default; not available on HTTP APIs
Private APINetwork path is through your interface endpointREST APIs onlyNetwork + resource policyNeeds VPC endpoint (hourly cost); no mTLS on private APIs
mTLSClient holds a private key for a certificate your CA chain trustsAny client, inside or outside AWSTLS handshake on a custom domainRegional 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_2 security 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.com endpoint 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 equivalentWhat's different
Managed identity + Entra ID token to call an APIIAM role + SigV4-signed request with AWS_IAM authNo token endpoint; the signature is the credential, per request
APIM validate-azure-ad-token for daemon appsAWS_IAM method authorisation, or Cognito client credentialsIAM is the native choice for AWS-to-AWS calls
APIM client certificate authenticationAPI Gateway mTLS on a Regional custom domainTruststore lives in S3; revocation is your job
App Service "Access restrictions" / Private EndpointResource policy + private REST API + interface VPC endpointPrivate APIs are a separate endpoint type, not a toggle
APIM in internal VNet modePrivate REST APIOne VPC endpoint can serve many private APIs
Azure RBAC role assignment on an APIIAM identity policy with execute-api:Invoke and a method ARNARNs 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:

CallerIdentity policyResource policyResult
Same account, AWS_IAM authAllownone / silentAllow
Same account, AWS_IAM authsilentAllowAllow
Same accountanyexplicit DenyDeny
Other account, AWS_IAM authAllowAllow for that account/roleAllow
Other accountAllowsilentDeny — 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

  1. Create an interface VPC endpoint for com.amazonaws.us-east-1.execute-api in private subnets, with a security group that allows 443 from your workloads.
  2. Create the REST API with endpoint type PRIVATE.
  3. Attach a resource policy that allows execute-api:Invoke only when aws:SourceVpce equals your endpoint ID (and denies otherwise). A private API with no resource policy can't be invoked.
  4. 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 an x-apigw-api-id header, 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

  1. Build the truststore: the issuing CA and every intermediate up to the root, concatenated in one .pem file. Upload it to a versioned S3 bucket with Block Public Access on.
  2. Request or import the server certificate for partner-api.harbourline.example in ACM in the same Region as the API.
  3. Create a Regional custom domain with security policy TLS_1_2 and --mutual-tls-authentication truststoreUri=s3://bucket/truststore.pem.
  4. Map the API stage to the domain (base path mapping) and create the DNS record.
  5. Disable the default execute-api endpoint on the API so nobody can bypass mTLS.
  6. 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

CallerRecommended control
Lambda, ECS, EC2 in your AWS organisationAWS_IAM + resource policy (aws:PrincipalOrgID), private API if no internet path is needed
On-premises system over Direct ConnectPrivate API via the VPC endpoint + IAM (IAM Roles Anywhere for credentials) or a Lambda authorizer
External partner over the internetmTLS on a Regional custom domain plus an OAuth client-credentials token or Lambda authorizer for per-partner authorisation
Customers in appsOAuth 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 fails

On 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

InternalApiStack.cs
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:

PartnerDomain.cs (excerpt)
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 = true

Complete 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):

Harbourline.MtlsLab/Program.cs
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.

PartnerClient.cs
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:

Harbourline.MtlsServer/Program.cs
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"]:

PartnerIdentity.cs
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

  1. 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.
  2. X509BasicConstraintsExtension(true, true, 0, true) — marks the root as a CA that may sign end-entity certificates only (path length 0).
  3. 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.
  4. clientRequest.Create(ca, ..., serial) — the CA signs the partner certificate. A random 128-bit serial lets you identify and revoke it.
  5. ExportCertificatePem() for the CA becomes truststore.pem. For a real chain, append the intermediate(s) and the root to the same file.
  6. X509Certificate2.CreateFromPemFile + LoadPkcs12 — loads the certificate and key; the PKCS#12 round trip avoids an ephemeral-key problem with SChannel on Windows.
  7. SslOptions.ClientCertificates — the handler offers the certificate during the TLS handshake. Server certificate validation stays on.
  8. ClientCertificateMode.RequireCertificate and CustomRootTrust — the local server mirrors API Gateway: only certificates chaining to the truststore pass.
  9. RevocationMode.NoCheck — deliberately mirrors API Gateway, which doesn't check revocation; the PartnerIdentity map (or a Lambda authorizer with a deny-list) is where revocation lives.
  10. 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-api endpoint; 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 grant execute-api:* (that includes ManageConnections and InvalidateCache).
  • Organisation guard rails. Add aws:PrincipalOrgID to 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.userArn or $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-deployment after 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 (apigateway instead of execute-api) → Credential should be scoped to correct service → the signing name for invoking APIs is execute-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-api endpoint in a shared VPC → other teams' calls to public APIs break → coordinate or use Route 53 aliases instead.

Troubleshooting

SymptomLikely causeFix
403 Missing Authentication TokenWrong path or stage, or unsigned request to an AWS_IAM methodCheck 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 APIResource policy missing or request not via the endpointAdd the aws:SourceVpce allow; check DNS resolves to the endpoint ENIs
403 The request signature we calculated does not matchProxy changed a header, or path not double-encodedSee the SigV4 lesson troubleshooting
TLS handshake failure from a partnerClient cert not chained to truststore, expired or unsupported algorithmopenssl verify -CAfile truststore.pem partner-client.pem
Domain shows certificate warnings after updateA certificate in the truststore is invalidDecode with openssl x509 -text, fix, upload a new version
Timeout calling a private API from a LambdaLambda not in the VPC, or endpoint security group blocks 443Put 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-1

Exercises

  • 🟢 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/*/balance and GET /internal/accounts/*/transactions on stage learn only, and denies everything on stage prod. 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

Knowledge check

Interview questions

  • "How do you secure service-to-service calls on AWS without secrets?" IAM roles for each workload, SigV4-signed requests, AWS_IAM authorisation 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

Completion checklist

  • I can write an execute-api:Invoke ARN 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:SourceVpce and 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.

On this page