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

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.

advanced⏱ 1 h 30 min🟢 FreeDVA-C03SCS-C03SAA-C03

Assumes: .NET 10 LTS · Lambda runtime dotnet10 · Amazon.Lambda.APIGatewayEvents 3.0.1 · Microsoft.IdentityModel 8.23.0 · xUnit v3 4.0.3 · 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:

  • Choose between a TOKEN and a REQUEST Lambda authorizer on a REST API, and configure an HTTP API Lambda authorizer (payload 1.0/2.0, simple responses).
  • Return the correct output: principalId, policyDocument, context, and know when API Gateway answers 401, 403 or 500.
  • Explain authorizer result caching (default 300 s, maximum 3,600 s) and fix the classic "policy cached for the wrong method" bug.
  • Write and unit-test a C# authorizer that validates a JWT against cached JWKS keys and passes customerId to the backend.
  • Decide when the built-in Cognito or JWT authorizer is the better choice.

Prerequisites

Why this matters in banking

Harbourline's partner-facing API must accept tokens from two identity providers (the bank's Cognito pool and a partner's OIDC server), reject tokens for customers whose KYC status is rejected, and tell the backend which customer_id is calling. No built-in authorizer can do all three. A Lambda authorizer can, but a single caching mistake can either lock customers out or, worse, let a decision made for one request be reused for another. Authorisation code is security-critical code: it needs tests, reviews and a clear design.

The idea in plain language

A Lambda authorizer (formerly "custom authorizer") is a Lambda function that API Gateway calls before your integration. It receives the caller's credentials (a header, query string, stage variables or context variables), decides, and returns:

  • a principal ID (who the caller is),
  • an IAM policy that allows or denies execute-api:Invoke on one or more method ARNs,
  • an optional context map that API Gateway forwards to your backend.

API Gateway can cache that answer for a while, keyed on the identity source, so the next request with the same token skips the Lambda call.

Analogy: The authorizer is the bank's reception desk. It checks your badge once and hands you a visitor slip listing every floor you may visit today. Lifts (API methods) only read the slip. If reception writes only "floor 3" because that is where you said you were going first, you will be stuck when you need floor 5 — and if it writes "all floors" without thinking, you can wander into the vault.

What problem the AWS service solves

Built-in authorizers cover standard cases without code: IAM (SigV4), Cognito user pools (REST), and JWT authorizers (HTTP APIs; the developer guide now also documents a JWT authorizer for REST APIs ⚠ VERIFY availability in your Region and tooling, because the REST CreateAuthorizer API reference still lists only TOKEN | REQUEST | COGNITO_USER_POOLS). A Lambda authorizer fills the gaps:

NeedBuilt-in enough?Lambda authorizer
Validate a Cognito access token and check scopesYes (Cognito/JWT authorizer)Not needed
Several issuers with different rulesJWT authorizer (multiple issuers) partlyYes
Opaque tokens that need introspection, HMAC-signed partner headers, legacy API tokensNoYes
Look up the customer, KYC status or consent before allowingNoYes
Check that a token's cnf thumbprint matches the mTLS client certificate (FAPI)NoYes (certificate is in the request context)

Limits and sharp edges (verified 2026-11-17):

  • Result caching: TTL default 300 s, maximum 3,600 s, 0 disables it (CreateAuthorizer). The cached policy is reused for every method that uses the authorizer, so it must cover all of them.
  • Context values on REST APIs must be strings, numbers or booleans — no arrays or objects; the backend receives them as strings in mapping templates.
  • Policy resource ARN in the authorizer output is limited to 512 characters; never put a JWT in the URL.
  • Identity sources: with caching on, a missing or empty identity source returns 401 without invoking the function.
  • Latency: a cold .NET start plus a JWKS download adds noticeable delay to the first request; caching and keeping the function small matter.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
APIM validate-jwt policyCognito or JWT authorizerConfiguration, no code
APIM policy calling an external auth service (send-request)Lambda authorizerRuns your code; returns an IAM policy, not a pass/fail flag (except HTTP API simple responses)
IAuthorizationHandler in ASP.NET CoreLambda authorizer + backend policiesThe authorizer runs at the edge; ownership checks still belong in the backend
APIM cache-store for auth resultsAuthorizer result cacheKeyed on identity sources; TTL up to 1 hour
HttpContext.User claimsrequestContext.authorizer in the Lambda proxy eventOnly flat string/number/boolean values on REST

Architecture

Security-boundary view: the authorizer is inside your trust boundary and is the only component that sees raw credentials. The backend trusts requestContext.authorizer only because nothing except API Gateway can invoke it (Lambda resource policy restricted to the API's ARN, no function URL). Ownership of ACC-… accounts is still checked by the backend query, not the authorizer.

Step-by-step implementation

Pick the authorizer type

TOKEN receives one header value (authorizationToken) and caches on it; it supports an optional regex (IdentityValidationExpression) that rejects malformed tokens before Lambda runs. REQUEST receives headers, query string, path, stage variables and context; it can use several identity sources as a composite cache key. AWS recommends REQUEST for new work. This lesson's code handles both.

Design a cache-safe policy

Decide the policy from the cache key alone (the token), not from the method being called. Map each scope to the routes it unlocks and return all of them, using wildcards in the ARN: arn:aws:execute-api:us-east-1:111122223333:a1b2c3d4e5/prod/GET/v1/*.

Write and test the function locally

Validate signature, issuer, lifetime, algorithm, token_use and client_id; fetch keys from the issuer's discovery document once and refresh only on an unknown kid. Run the xUnit tests with tokens signed by a local RSA key — no AWS needed.

Deploy and attach (optional)

Create the function on dotnet10 (ARM64), the authorizer, and grant API Gateway permission to invoke it. Test with test-invoke-authorizer.

AWS Console instructions

Console → API Gateway → APIs → (your REST API) → Authorizers → Create authorizer: type Lambda, choose the function, Lambda event payload Token (token source Authorization, optional validation regex) or Request (add Header Authorization), keep Authorization caching on with TTL 300. Leave Lambda invoke role empty so the console adds a resource-based permission. Then Resources → method → Method request → Edit → Authorizer, select it, and Deploy API. The Test authorizer button shows the returned policy; note that in the console test a Deny still shows 200, while real calls get 403.

AWS CLI

# Package (Amazon.Lambda.Tools: dotnet tool install -g Amazon.Lambda.Tools)
cd src/Harbourline.Authorizer
dotnet lambda package -c Release -o ../../authorizer.zip --function-architecture arm64
cd ../..
export AWS_PROFILE=learn-sandbox AWS_REGION=us-east-1
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)

# Log group with retention BEFORE the function writes to it
aws logs create-log-group --log-group-name /aws/lambda/hl-m04-authorizer \
  --tags Project=cea-lab,Lab=m04-authorizer,Environment=learn,Owner=<your-name>
aws logs put-retention-policy --log-group-name /aws/lambda/hl-m04-authorizer --retention-in-days 7

# Execution role (logs only; the function calls no AWS APIs)
aws iam create-role --role-name hl-m04-authorizer-role \
  --assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}' \
  --tags Key=Project,Value=cea-lab Key=Lab,Value=m04-authorizer Key=Environment,Value=learn Key=Owner,Value=<your-name>
aws iam attach-role-policy --role-name hl-m04-authorizer-role \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

# env.json: {"Variables":{"JWT_ISSUER":"https://cognito-idp.us-east-1.amazonaws.com/<poolId>",
#   "ALLOWED_CLIENT_IDS":"<web-client-id>","CUSTOMER_MAP":"{\"<sub>\":\"CUS-00012345\"}"}}
aws lambda create-function --function-name hl-m04-authorizer \
  --runtime dotnet10 --architectures arm64 --memory-size 512 --timeout 5 \
  --handler 'Harbourline.Authorizer::Harbourline.Authorizer.Function::HandleAsync' \
  --zip-file fileb://authorizer.zip \
  --role "arn:aws:iam::$ACCOUNT:role/hl-m04-authorizer-role" \
  --environment file://env.json \
  --tags Project=cea-lab,Lab=m04-authorizer,Environment=learn,Owner=<your-name>

# TOKEN authorizer with a 300 s cache and a format check before Lambda runs
AUTH_ID=$(aws apigateway create-authorizer --rest-api-id "$API_ID" \
  --name hl-m04-jwt-authorizer --type TOKEN \
  --authorizer-uri "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:$ACCOUNT:function:hl-m04-authorizer/invocations" \
  --identity-source method.request.header.Authorization \
  --identity-validation-expression '^Bearer [-0-9A-Za-z_]+\.[-0-9A-Za-z_]+\.[-0-9A-Za-z_]+$' \
  --authorizer-result-ttl-in-seconds 300 --query id --output text)

# Allow ONLY this API's authorizer to invoke the function
aws lambda add-permission --function-name hl-m04-authorizer \
  --statement-id apigw-authorizer --action lambda:InvokeFunction \
  --principal apigateway.amazonaws.com \
  --source-arn "arn:aws:execute-api:us-east-1:$ACCOUNT:$API_ID/authorizers/$AUTH_ID"

# Try it without a client
aws apigateway test-invoke-authorizer --rest-api-id "$API_ID" \
  --authorizer-id "$AUTH_ID" --headers Authorization="Bearer $ACCESS"

For an HTTP API, the equivalent is aws apigatewayv2 create-authorizer --authorizer-type REQUEST --identity-source '$request.header.Authorization' --authorizer-payload-format-version 2.0 --enable-simple-responses --authorizer-result-ttl-in-seconds 300 with the handler ...::HandleHttpApiAsync.

Infrastructure as Code

using Amazon.CDK;
using Amazon.CDK.AWS.APIGateway;
using Amazon.CDK.AWS.Lambda;

// inside a Stack: authorizerFunction is the dotnet10 Function, api is the RestApi
var authorizer = new RequestAuthorizer(this, "JwtAuthorizer", new RequestAuthorizerProps
{
    AuthorizerName = "hl-m04-jwt-authorizer",
    Handler = authorizerFunction,
    IdentitySources = [IdentitySource.Header("Authorization")],
    ResultsCacheTtl = Duration.Minutes(5),
});

api.Root.AddResource("v1").AddResource("accounts").AddMethod("GET", integration, new MethodOptions
{
    Authorizer = authorizer,
    AuthorizationType = AuthorizationType.CUSTOM,
});

CDK adds the lambda:InvokeFunction permission scoped to the API for you.

Complete code

Three source files and one test file. The projects target net10.0 with nullable and warnings-as-errors on; packages: Amazon.Lambda.Core 3.4.0, Amazon.Lambda.APIGatewayEvents 3.0.1, Amazon.Lambda.Serialization.SystemTextJson 3.0.1, Microsoft.IdentityModel.JsonWebTokens and Microsoft.IdentityModel.Protocols.OpenIdConnect 8.23.0; tests add xunit.v3 4.0.3 and Amazon.Lambda.TestUtilities 4.3.0. All tests pass with dotnet test and no AWS account.

src/Harbourline.Authorizer/AccessTokenValidator.cs
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;

namespace Harbourline.Authorizer;

public sealed record AuthorizerSettings(string Issuer, IReadOnlySet<string> AllowedClientIds)
{
    public static AuthorizerSettings FromEnvironment() => new(
        Environment.GetEnvironmentVariable("JWT_ISSUER")
            ?? throw new InvalidOperationException("JWT_ISSUER is not set."),
        (Environment.GetEnvironmentVariable("ALLOWED_CLIENT_IDS") ?? "")
            .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
            .ToHashSet(StringComparer.Ordinal));
}

public sealed record ValidatedCaller(string Subject, string ClientId, IReadOnlySet<string> Scopes);

public interface ISigningKeyProvider
{
    Task<IEnumerable<SecurityKey>> GetKeysAsync(bool forceRefresh, CancellationToken ct);
}

public sealed class OidcSigningKeyProvider(string issuer) : ISigningKeyProvider
{
    private readonly ConfigurationManager<OpenIdConnectConfiguration> _manager = new(
        $"{issuer}/.well-known/openid-configuration",
        new OpenIdConnectConfigurationRetriever(),
        new HttpDocumentRetriever { RequireHttps = true });

    public async Task<IEnumerable<SecurityKey>> GetKeysAsync(bool forceRefresh, CancellationToken ct)
    {
        if (forceRefresh) _manager.RequestRefresh();
        var configuration = await _manager.GetConfigurationAsync(ct);
        return configuration.SigningKeys;
    }
}

public sealed class AccessTokenValidator(AuthorizerSettings settings, ISigningKeyProvider keys)
{
    private readonly JsonWebTokenHandler _handler = new() { MapInboundClaims = false };

    public async Task<ValidatedCaller?> ValidateAsync(string? authorizationHeader, CancellationToken ct)
    {
        const string prefix = "Bearer ";
        if (authorizationHeader is null ||
            !authorizationHeader.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
            return null;

        var token = authorizationHeader[prefix.Length..].Trim();
        var result = await ValidateOnceAsync(token, forceRefresh: false, ct);
        if (result.Exception is SecurityTokenSignatureKeyNotFoundException)
            result = await ValidateOnceAsync(token, forceRefresh: true, ct);
        if (!result.IsValid) return null;

        if (Claim(result, "token_use") != "access") return null;
        var clientId = Claim(result, "client_id");
        if (clientId is null || !settings.AllowedClientIds.Contains(clientId)) return null;
        var subject = Claim(result, "sub");
        if (string.IsNullOrEmpty(subject)) return null;

        var scopes = (Claim(result, "scope") ?? "")
            .Split(' ', StringSplitOptions.RemoveEmptyEntries)
            .ToHashSet(StringComparer.Ordinal);
        return new ValidatedCaller(subject, clientId, scopes);
    }

    private async Task<TokenValidationResult> ValidateOnceAsync(string token, bool forceRefresh, CancellationToken ct)
    {
        var parameters = new TokenValidationParameters
        {
            ValidIssuer = settings.Issuer,
            ValidateAudience = false,
            ValidateLifetime = true,
            RequireExpirationTime = true,
            ClockSkew = TimeSpan.FromSeconds(30),
            ValidAlgorithms = [SecurityAlgorithms.RsaSha256],
            IssuerSigningKeys = await keys.GetKeysAsync(forceRefresh, ct),
        };
        return await _handler.ValidateTokenAsync(token, parameters);
    }

    private static string? Claim(TokenValidationResult result, string name) =>
        result.Claims.TryGetValue(name, out var value) ? value as string : null;
}
src/Harbourline.Authorizer/PolicyBuilder.cs
using Amazon.Lambda.APIGatewayEvents;

namespace Harbourline.Authorizer;

public static class PolicyBuilder
{
    // Scope -> routes it unlocks. The policy depends ONLY on the token (the cache key),
    // never on the path of the request that happened to arrive first.
    private static readonly (string Scope, string VerbAndPath)[] Grants =
    [
        ("harbourline-accounts/accounts.read", "GET/v1/*"),
        ("harbourline-accounts/statements.write", "POST/v1/accounts/*/statement-requests"),
    ];

    // arn:aws:execute-api:us-east-1:111122223333:a1b2c3d4e5/prod/GET/v1/accounts
    //   -> arn:aws:execute-api:us-east-1:111122223333:a1b2c3d4e5/prod
    public static string ApiStageArn(string methodArn)
    {
        var parts = methodArn.Split('/');
        if (parts.Length < 3 || !parts[0].StartsWith("arn:aws:execute-api:", StringComparison.Ordinal))
            throw new ArgumentException("Unexpected method ARN.", nameof(methodArn));
        return $"{parts[0]}/{parts[1]}";
    }

    public static APIGatewayCustomAuthorizerResponse ForCaller(
        ValidatedCaller caller, string methodArn, string customerId)
    {
        var apiStage = ApiStageArn(methodArn);
        var allowed = Grants
            .Where(g => caller.Scopes.Contains(g.Scope))
            .Select(g => $"{apiStage}/{g.VerbAndPath}")
            .ToHashSet(StringComparer.Ordinal);

        if (allowed.Count == 0) return Deny(caller.Subject, methodArn);

        return new APIGatewayCustomAuthorizerResponse
        {
            PrincipalID = caller.Subject,
            PolicyDocument = Policy("Allow", allowed),
            Context = new APIGatewayCustomAuthorizerContextOutput
            {
                ["customerId"] = customerId,
                ["clientId"] = caller.ClientId,
                ["scope"] = string.Join(' ', caller.Scopes.Order(StringComparer.Ordinal)),
            },
        };
    }

    public static APIGatewayCustomAuthorizerResponse Deny(string principalId, string methodArn) => new()
    {
        PrincipalID = principalId,
        PolicyDocument = Policy("Deny", [$"{ApiStageArn(methodArn)}/*"]),
    };

    private static APIGatewayCustomAuthorizerPolicy Policy(string effect, HashSet<string> resources) => new()
    {
        Version = "2012-10-17",
        Statement =
        [
            new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement
            {
                Effect = effect,
                Action = ["execute-api:Invoke"],
                Resource = resources,
            },
        ],
    };
}
src/Harbourline.Authorizer/Function.cs
using System.Text.Json;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.SystemTextJson;

[assembly: LambdaSerializer(typeof(DefaultLambdaJsonSerializer))]

namespace Harbourline.Authorizer;

/// <summary>API Gateway turns an error whose message is exactly "Unauthorized" into HTTP 401.</summary>
public sealed class UnauthorizedException() : Exception("Unauthorized");

public interface ICustomerDirectory
{
    Task<string?> FindCustomerIdAsync(string subject, CancellationToken ct);
}

/// <summary>Lab-only directory seeded from CUSTOMER_MAP, e.g. {"sub-1":"CUS-00012345"}.</summary>
public sealed class InMemoryCustomerDirectory(IReadOnlyDictionary<string, string> map) : ICustomerDirectory
{
    public static InMemoryCustomerDirectory FromEnvironment() => new(
        JsonSerializer.Deserialize<Dictionary<string, string>>(
            Environment.GetEnvironmentVariable("CUSTOMER_MAP") ?? "{}") ?? []);

    public Task<string?> FindCustomerIdAsync(string subject, CancellationToken ct) =>
        Task.FromResult(map.TryGetValue(subject, out var id) ? id : null);
}

public sealed class Function
{
    private readonly AccessTokenValidator _validator;
    private readonly ICustomerDirectory _customers;

    // Lambda calls this once per execution environment, so the JWKS cache survives warm invocations.
    public Function() : this(CreateValidator(), InMemoryCustomerDirectory.FromEnvironment()) { }

    public Function(AccessTokenValidator validator, ICustomerDirectory customers)
    {
        _validator = validator;
        _customers = customers;
    }

    public async Task<APIGatewayCustomAuthorizerResponse> HandleAsync(
        APIGatewayCustomAuthorizerRequest request, ILambdaContext context)
    {
        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));

        var header = request.AuthorizationToken ?? FindHeader(request.Headers, "Authorization");
        var caller = await _validator.ValidateAsync(header, cts.Token);
        if (caller is null)
        {
            context.Logger.LogInformation("Rejected token (details withheld).");
            throw new UnauthorizedException();
        }

        var customerId = await _customers.FindCustomerIdAsync(caller.Subject, cts.Token);
        if (customerId is null)
        {
            context.Logger.LogInformation($"No customer for principal {caller.Subject}.");
            return PolicyBuilder.Deny(caller.Subject, request.MethodArn);
        }

        return PolicyBuilder.ForCaller(caller, request.MethodArn, customerId);
    }

    // HTTP API variant: payload format 2.0 with simple responses enabled.
    public async Task<APIGatewayCustomAuthorizerV2SimpleResponse> HandleHttpApiAsync(
        APIGatewayCustomAuthorizerV2Request request, ILambdaContext context)
    {
        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
        var caller = await _validator.ValidateAsync(FindHeader(request.Headers, "Authorization"), cts.Token);
        var customerId = caller is null ? null : await _customers.FindCustomerIdAsync(caller.Subject, cts.Token);

        return new APIGatewayCustomAuthorizerV2SimpleResponse
        {
            IsAuthorized = customerId is not null,
            Context = customerId is null ? new() : new() { ["customerId"] = customerId },
        };
    }

    private static AccessTokenValidator CreateValidator()
    {
        var settings = AuthorizerSettings.FromEnvironment();
        return new AccessTokenValidator(settings, new OidcSigningKeyProvider(settings.Issuer));
    }

    private static string? FindHeader(IDictionary<string, string>? headers, string name) =>
        headers?.FirstOrDefault(h => string.Equals(h.Key, name, StringComparison.OrdinalIgnoreCase)).Value;
}
tests/Harbourline.Authorizer.Tests/FunctionTests.cs
using System.Security.Cryptography;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.TestUtilities;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;

namespace Harbourline.Authorizer.Tests;

public sealed class FunctionTests
{
    private const string Issuer = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_Test";
    private const string GetAccountsArn =
        "arn:aws:execute-api:us-east-1:111122223333:a1b2c3d4e5/prod/GET/v1/accounts";
    private static readonly RsaSecurityKey SigningKey = new(RSA.Create(2048)) { KeyId = "test-key-1" };

    private sealed class StaticKeys : ISigningKeyProvider
    {
        public Task<IEnumerable<SecurityKey>> GetKeysAsync(bool forceRefresh, CancellationToken ct) =>
            Task.FromResult<IEnumerable<SecurityKey>>([SigningKey]);
    }

    private static Function CreateFunction() => new(
        new AccessTokenValidator(
            new AuthorizerSettings(Issuer, new HashSet<string> { "web-client" }), new StaticKeys()),
        new InMemoryCustomerDirectory(new Dictionary<string, string> { ["user-123"] = "CUS-00012345" }));

    private static string Mint(string tokenUse = "access", string clientId = "web-client",
        string scope = "harbourline-accounts/accounts.read", DateTime? expires = null)
    {
        var exp = expires ?? DateTime.UtcNow.AddMinutes(15);
        return new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor
        {
            Issuer = Issuer,
            IssuedAt = exp.AddMinutes(-15),
            NotBefore = exp.AddMinutes(-15),
            Expires = exp,
            SigningCredentials = new SigningCredentials(SigningKey, SecurityAlgorithms.RsaSha256),
            Claims = new Dictionary<string, object>
            {
                ["sub"] = "user-123", ["token_use"] = tokenUse, ["client_id"] = clientId, ["scope"] = scope,
            },
        });
    }

    private static APIGatewayCustomAuthorizerRequest TokenRequest(string token) => new()
    {
        Type = "TOKEN",
        AuthorizationToken = $"Bearer {token}",
        MethodArn = GetAccountsArn,
    };

    [Fact]
    public async Task Valid_access_token_is_allowed_with_customer_context()
    {
        var response = await CreateFunction().HandleAsync(TokenRequest(Mint()), new TestLambdaContext());

        var statement = Assert.Single(response.PolicyDocument.Statement);
        Assert.Equal("Allow", statement.Effect);
        Assert.Contains("arn:aws:execute-api:us-east-1:111122223333:a1b2c3d4e5/prod/GET/v1/*", statement.Resource);
        Assert.Equal("CUS-00012345", response.Context["customerId"]);
    }

    [Fact]
    public async Task Policy_does_not_depend_on_the_first_requested_path()
    {
        var token = Mint(scope: "harbourline-accounts/accounts.read harbourline-accounts/statements.write");

        var response = await CreateFunction().HandleAsync(TokenRequest(token), new TestLambdaContext());

        Assert.Contains(
            "arn:aws:execute-api:us-east-1:111122223333:a1b2c3d4e5/prod/POST/v1/accounts/*/statement-requests",
            response.PolicyDocument.Statement[0].Resource);
    }

    [Theory]
    [InlineData("id", "web-client")]
    [InlineData("access", "marketing-client")]
    public async Task Wrong_token_use_or_client_is_unauthorized(string tokenUse, string clientId) =>
        await Assert.ThrowsAsync<UnauthorizedException>(() =>
            CreateFunction().HandleAsync(TokenRequest(Mint(tokenUse, clientId)), new TestLambdaContext()));

    [Fact]
    public async Task Expired_token_is_unauthorized() =>
        await Assert.ThrowsAsync<UnauthorizedException>(() =>
            CreateFunction().HandleAsync(
                TokenRequest(Mint(expires: DateTime.UtcNow.AddMinutes(-5))), new TestLambdaContext()));

    [Fact]
    public async Task Token_without_known_scopes_is_denied()
    {
        var response = await CreateFunction().HandleAsync(
            TokenRequest(Mint(scope: "aws.cognito.signin.user.admin")), new TestLambdaContext());

        Assert.Equal("Deny", response.PolicyDocument.Statement[0].Effect);
    }
}

Code explained line by line

  1. AuthorizerSettings.FromEnvironment reads the issuer and the client allow-list from environment variables, so the same code serves test and production pools.
  2. ISigningKeyProvider is the seam that makes the validator unit-testable: production uses OidcSigningKeyProvider, tests use StaticKeys with a local RSA key.
  3. ConfigurationManager<OpenIdConnectConfiguration> downloads /.well-known/openid-configuration, follows jwks_uri, caches the keys (it refreshes automatically, by default every 12 hours) and is thread-safe.
  4. RequestRefresh() on SecurityTokenSignatureKeyNotFoundException handles key rotation: an unknown kid triggers one refresh and one retry, not a refresh per request.
  5. TokenValidationParameters enforce issuer, lifetime with 30 s skew, mandatory exp and RS256 only. Audience is skipped because Cognito access tokens have none; the client_id allow-list replaces it.
  6. token_use / client_id / sub checks reject ID tokens, tokens for other app clients and malformed tokens.
  7. PolicyBuilder.Grants maps scopes to route patterns. Because the result is computed from the token only, a cached policy is correct for any later method called with the same token.
  8. ApiStageArn keeps the API ID and stage from methodArn and replaces verb and path with wildcards, so the policy never names only the first method.
  9. Deny returns an explicit Deny for the whole stage → API Gateway answers 403. Use it when the token is valid but the caller is not allowed (no customer record, no usable scope).
  10. UnauthorizedException has the exact message Unauthorized; API Gateway maps that to 401. Any other unhandled exception becomes 500, which clients would retry: never leak exceptions for bad tokens.
  11. context carries customerId, clientId and scope as flat strings. With the Lambda proxy integration the backend reads them from requestContext.authorizer.
  12. The parameterless constructor builds real dependencies once per execution environment; the second constructor is for tests and for a future DynamoDB-backed ICustomerDirectory.
  13. The 3-second CancellationTokenSource bounds JWKS and lookup calls so a slow dependency fails fast instead of holding the request.
  14. HandleHttpApiAsync shows the HTTP API 2.0 simple response: a Boolean plus context. Simple responses allow or deny every route for the cached identity, so use them only when all routes share one rule.
  15. Tests mint real RS256 tokens with JsonWebTokenHandler and assert on Allow/Deny, resources and 401 behaviour, including the cache-safety property.

Security considerations

⚠ Learning shortcut — not for production

InMemoryCustomerDirectory reads a JSON map from an environment variable. In production, look customers up in a DynamoDB table or the customer service (cached for a short time), and keep the authorizer's IAM role limited to that one read. Environment variables are visible to anyone with lambda:GetFunctionConfiguration.

The classic caching bug, and its fix. Many samples return Resource = event.methodArn. With caching on, the first call (GET /v1/accounts) stores a policy that allows only that method. The customer's next call with the same token (POST …/statement-requests) hits the cache, the policy does not match, and API Gateway returns 403 for a perfectly valid request. The dangerous variant is the opposite: an authorizer that inspects the path ("may this customer see ACC-0000012345?"), returns a broad Allow, and caches it — the next request for someone else's account reuses the decision. Fixes, in order of preference:

  1. Make the decision a function of the cache key only, and return wildcard resources covering every method the token may call (this lesson's code).
  2. If the decision must depend on the route, use a REQUEST authorizer and add the route to the identity sources (context.httpMethod and context.resourcePath on REST, $context.routeKey on HTTP APIs), accepting a lower cache hit rate.
  3. Turn caching off (TTL 0) and pay for every invocation.

In every case, ownership checks stay in the backend (the lab's IAccountStore.GetAccountAsync(customerId, accountId) returns 404 for other customers' accounts).

Also: never log tokens; restrict the Lambda resource policy to the authorizer ARN; keep TTL shorter than the access-token lifetime if you rely on revocation; and remember a cached Allow survives until the TTL ends even if you disable the user.

Banking use case

Harbourline exposes GET /v1/accounts to a partner budgeting app under a customer's consent. The authorizer validates the partner-issued access token, checks that consent CNS-… for CUS-00012345 is active in the consent store, and returns a policy for GET/v1/* only, with customerId and consentId in the context. The backend uses customerId to filter accounts and writes consentId to the audit log (audit_events.actor). Consent rules and data sharing must be reviewed by compliance against the bank's Open Banking obligations; see Open Banking / PSD2 and FAPI.

Common mistakes

  • Returning Resource = methodArn with caching on → random 403s on other methods → return wildcard resources computed from the token.
  • Throwing for every failure → expired tokens return 500 and clients retry → throw exactly Unauthorized for bad credentials, return Deny for "valid but not allowed".
  • Downloading JWKS on every call → slow and rate-limited → cache keys outside the handler.
  • Trusting context in a backend that is also publicly reachable → anyone can forge "customerId" → only API Gateway may invoke the backend.
  • Writing a Lambda authorizer for plain Cognito scope checks → extra cost and latency → use the Cognito or JWT authorizer.

Troubleshooting

SymptomLikely causeFix
401 and the function is never invokedIdentity source header missing/empty, or TOKEN regex did not matchSend Authorization: Bearer …; test the regex
500 AuthorizerConfigurationExceptionAPI Gateway cannot invoke the function, or the output is malformedCheck add-permission source ARN; validate JSON field names (principalId, policyDocument)
403 on the second endpoint onlyCached policy names only the first methodWildcard resources or route in cache key
Works in console test, 403 for realDeny policy (console shows 200 for Deny)Read the returned policy
First request slow, others fastCold start plus JWKS downloadSmaller package, ARM64, SnapStart where supported ⚠ VERIFY for dotnet10, keep caching on
IDX10503 signature failed after a key rotationOld keys cached and no refresh on unknown kidRefresh on SecurityTokenSignatureKeyNotFoundException

Cost and cleanup

Cost: free for local tests. Deployed, the authorizer is a normal Lambda function (free tier 1 million requests and 400,000 GB-seconds per month; then USD 0.20 per million requests plus compute), and caching cuts invocations. REST API calls cost USD 3.50 per million in us-east-1 after any free tier.

aws apigateway delete-authorizer --rest-api-id "$API_ID" --authorizer-id "$AUTH_ID"  # detach from methods first
aws lambda delete-function --function-name hl-m04-authorizer
aws iam detach-role-policy --role-name hl-m04-authorizer-role \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
aws iam delete-role --role-name hl-m04-authorizer-role
aws logs delete-log-group --log-group-name /aws/lambda/hl-m04-authorizer
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab --profile learn-sandbox

Exercises

  • 🟢 Guided: Run the tests. Then change PolicyBuilder.ForCaller to return only methodArn and write a test that shows the cached policy would not allow POST …/statement-requests.
  • 🟡 Challenge: Add a second issuer (a partner's OIDC server) with its own allow-list. Pick the issuer from the unvalidated iss claim, but validate against that issuer's keys only.
  • 🔴 Live problem: After enabling caching with TTL 3600, customers who were blocked by fraud operations can still use the API for up to an hour. Product wants caching for cost reasons. Propose a design.

Assignment

Publish the authorizer in your portfolio repository with a README that states: the threat model (what it trusts), the cache key, the policy shape, why 401 vs 403, and a table of tests. Add a GitHub Actions job that runs dotnet test.

Solutions

Knowledge check

Interview questions

  • TOKEN vs REQUEST authorizer? TOKEN reads one header and caches on it, with an optional regex pre-check; REQUEST sees headers, query, path, stage and context variables and can build a composite cache key. Prefer REQUEST for new work.
  • Describe the authorizer caching pitfall. The cached policy is reused across methods; if it was computed for one method it either blocks others or over-grants. Compute it from the cache key only, or put the route into the key.
  • How do you validate JWTs efficiently in Lambda? Cache the discovery document and keys outside the handler, refresh on unknown kid, restrict algorithms, validate iss, exp, and the token-type and client claims.
  • Where do ownership checks belong? In the backend data access, using the caller identity from the authorizer context; the authorizer decides "may call this route", not "may see this row".
  • How would you check a certificate-bound token? In a REQUEST authorizer on an mTLS custom domain, compare the token's cnf x5t#S256 with the SHA-256 thumbprint of the client certificate in the request context.

Certification practice

Completion checklist

  • I can explain TOKEN vs REQUEST and HTTP API simple responses
  • I ran the authorizer tests locally and understood each one
  • I can explain the caching bug and two fixes
  • I deleted any deployed authorizer, function, role and log group

Key takeaways

  • A Lambda authorizer returns principal, IAM policy and context; API Gateway caches it (300 s default, 3,600 s max) per identity source.
  • Compute cached policies from the cache key only and use wildcard resources; keep ownership checks in the backend.
  • Unauthorized → 401, Deny policy → 403, anything else → 500.
  • Prefer built-in Cognito/JWT authorizers for standard JWTs; use Lambda for custom credentials, lookups or certificate binding.

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