Skip to content

AWS Cognito + Verified Permissions for SaaS Authorization

Build SaaS authorization with AWS Cognito and Verified Permissions, covering Cedar policies, multi-tenant patterns, JWT flow, and cost in TypeScript.

Ayhan Sipahi Ayhan Sipahi

Authentication is the easy half of a B2B SaaS build on AWS. Cognito signs users in and hands back a JWT, but a valid token says nothing about whether tenant A may read tenant B’s documents. AWS Verified Permissions (AVP) is the managed service that answers that second question, and the default worth starting from is the pool model: one Cognito User Pool, one AVP policy store, and a tenant check inside every Cedar policy.

Three decisions carry most of the weight: which token carries the tenant claims into AVP, whether tenant isolation lives in Cedar policy or in separate infrastructure per tenant, and which AVP API each call path uses. Cedar policy shape, TypeScript wiring, and the monthly bill all follow from those three.

Note

This is Part 2 of the External Authorization Systems series. Part 1 covers the broader authorization platform landscape and decision framework.

Cognito’s Role in Authorization#

Cognito is an authentication service, not an authorization engine. But authentication and authorization are tightly coupled in SaaS systems. Cognito’s output (JWT tokens with claims) becomes the input for authorization decisions.

JWT Tokens and Claims#

After a user authenticates, Cognito issues three tokens:

  • ID Token: Contains user identity claims (email, name, custom attributes). Used for user profile information.
  • Access Token: Contains scopes and authorization-related claims. Used for API authorization.
  • Refresh Token: Used to obtain new ID and access tokens without re-authentication.

Which Token AVP Reads#

AVP treats the two tokens differently. In ID token authorization, it maps claims to attributes of the principal entity. For access tokens, the AVP user guide says it processes claims other than the groups claim “as attributes of the action, or context attributes”. A policy then reads them under context.token, for example context.token.tenantId.

The recommended setup sends the ID token to AVP, for three reasons:

  • Tenant and role claims land on the principal, so policies read principal.tenantId and principal.orgRole. The AVP console’s guided setup can also fill the schema from the user pool’s attributes.
  • A Pre Token Generation trigger with a V1_0 event can add claims to the ID token, and the Lite plan includes that event version. Adding claims to the access token needs a V2_0 event, which needs the Essentials or Plus plan.
  • One token carries everything AVP needs about the user. The request adds only the resource.

The trade-off is scopes. ID tokens carry no OAuth scopes, so an API Gateway route can’t require one, and the API Gateway JWT authorizer guide recommends route scopes unless you require ID tokens for API authorization. Keep the ID token inside your own API and don’t forward it to third-party services. If you need scopes, or you already pay for Essentials, use the access token instead: add the claims with a V2_0 trigger, map them under a token record in each action’s context in the schema, and write conditions as context.token.tenantId == resource.tenantId. Decide early. The AVP guide warns that changing the token type later takes significant refactoring of policies and schema.

Custom Claims and Tenant Context#

Cognito supports custom attributes on user profiles (prefixed with custom:). For SaaS, the critical custom attributes are tenant identifiers and organizational roles:

  • custom:tenantId: the tenant this user belongs to
  • custom:orgRole: the user’s role within the tenant (admin, editor, viewer)
  • custom:tenantTier: the tenant’s subscription tier (free, pro, enterprise)

Your backend sets these attributes with an admin API when it creates or updates the user, and Cognito includes them in the ID token. They are not read-only by default. An app client without an explicit WriteAttributes list can write every standard and custom attribute, and users can change those values for themselves with UpdateUserAttributes. A user who can rewrite custom:tenantId or custom:orgRole walks past every Cedar tenant check with a forged value.

Locking Tenant Attributes#

The fix is configuration: make tenantId immutable, and leave all three tenant attributes out of the writeAttributes of every app client in the pool. User attributes are shared by all app clients, so one permissive client is enough to leak.

// User pool and app client with tenant attributes locked against self-service edits

import { Duration } from "aws-cdk-lib";
import * as cognito from "aws-cdk-lib/aws-cognito";
import type * as lambda from "aws-cdk-lib/aws-lambda";
import type { Construct } from "constructs";

export function createSaasUserPool(scope: Construct, preTokenFn: lambda.IFunction) {
  const userPool = new cognito.UserPool(scope, "SaasUsers", {
    featurePlan: cognito.FeaturePlan.LITE,
    customAttributes: {
      // Immutable: written once when your backend creates the user
      tenantId: new cognito.StringAttribute({ mutable: false }),
      // Mutable, but only through admin APIs (see writeAttributes below)
      orgRole: new cognito.StringAttribute({ mutable: true }),
      tenantTier: new cognito.StringAttribute({ mutable: true }),
    },
  });

  // No version argument: the trigger receives V1_0 events (ID token only)
  userPool.addTrigger(cognito.UserPoolOperation.PRE_TOKEN_GENERATION, preTokenFn);

  // Users may edit their display name and nothing else.
  // An app client without writeAttributes can write every attribute.
  const writeAttributes = new cognito.ClientAttributes()
    .withStandardAttributes({ fullname: true });

  const readAttributes = new cognito.ClientAttributes()
    .withStandardAttributes({ fullname: true, email: true, emailVerified: true })
    .withCustomAttributes("tenantId", "orgRole", "tenantTier");

  const client = userPool.addClient("WebClient", {
    readAttributes,
    writeAttributes,
    idTokenValidity: Duration.minutes(15),
    accessTokenValidity: Duration.minutes(15),
    refreshTokenValidity: Duration.days(30),
  });

  return { userPool, client };
}

Verify the lock with a regular user’s session. UpdateUserAttributes is authorized with the user’s access token, so sign in as a test user and try to promote yourself:

aws cognito-idp update-user-attributes \
  --access-token "$USER_ACCESS_TOKEN" \
  --user-attributes Name=custom:orgRole,Value=admin

The call should fail with a NotAuthorizedException. If it succeeds, some app client can still write the attribute. Run this check in CI against a test pool, next to the cross-tenant Cedar test described under Common Mistakes.

Pre Token Generation Trigger#

The Pre Token Generation Lambda trigger runs before Cognito issues tokens: at sign-in and again on every refresh (TokenGeneration_RefreshTokens). With a V1_0 event it adds claims to the ID token. Here it copies the tenant attributes into short claim names. Cedar can read principal.tenantId directly, while a custom: claim needs bracket notation (principal["custom:tenantId"]).

// Pre Token Generation trigger, V1_0 event: adds tenant claims to the ID token
// V1_0 is the event version that user pools on the Lite plan receive

import type { PreTokenGenerationTriggerEvent } from "aws-lambda";

export const handler = async (event: PreTokenGenerationTriggerEvent) => {
  const attrs = event.request.userAttributes;

  // AVP maps ID token claims to principal attributes:
  // these become principal.tenantId, principal.orgRole, principal.tenantTier
  event.response = {
    claimsOverrideDetails: {
      claimsToAddOrOverride: {
        tenantId: attrs["custom:tenantId"],
        orgRole: attrs["custom:orgRole"],
        tenantTier: attrs["custom:tenantTier"],
      },
    },
  };

  return event;
};

Because the trigger runs on every issue and refresh, it is also the place to take user attributes out of the trust path. Read the user’s tenant membership and role from your own tenant table here, so each new token carries the values from your database.

Tip

Keep custom claims minimal. Every claim travels with every API call and every AVP request. Only include claims that Cedar policies actively evaluate.

User Pool vs. Identity Pool#

Cognito has two components that serve different purposes:

  • User Pool: Manages user authentication (sign-up, sign-in, MFA, password recovery). Issues JWT tokens. This is where tenant context lives.
  • Identity Pool: Maps authenticated users to temporary AWS credentials (IAM roles). Used for direct AWS resource access (S3, DynamoDB).

For SaaS authorization with AVP, you primarily use the User Pool. The Identity Pool is relevant only if your application needs direct AWS resource access from the client side.

AWS Verified Permissions Deep Dive#

AVP is a managed authorization service that uses the Cedar policy language. It evaluates authorization requests against Cedar policies and returns allow or deny decisions.

Cedar Policy Language#

Cedar is declarative and statically analyzable. Its authorizer and type checker have machine-checked proofs in Lean: a satisfied forbid policy denies the request, a request with no satisfied permit is denied, and a policy that passes the type checker can’t fail with a type error at evaluation. The proofs cover the language. Whether your own policies isolate tenants is still yours to test. Policies express who (principal) can do what (action) to which resource, under what conditions.

A basic Cedar policy:

// Allow tenant admins to manage all documents within their tenant
permit(
  principal,
  action in [
    SaasApp::Action::"ViewDocument",
    SaasApp::Action::"EditDocument",
    SaasApp::Action::"DeleteDocument",
    SaasApp::Action::"RestoreDocument"
  ],
  resource
)
when {
  principal.orgRole == "admin" &&
  principal.tenantId == resource.tenantId
};

Cedar supports two policy types:

  • permit: Grants access when conditions match
  • forbid: Denies access even if a permit policy matches (forbid always wins)

This “deny overrides permit” model makes it straightforward to add safety constraints:

// Forbid access to archived documents regardless of role,
// except the restore action itself
forbid(
  principal,
  action,
  resource is SaasApp::Document
)
when {
  resource.status == "archived"
}
unless {
  action == SaasApp::Action::"RestoreDocument"
};

Without the unless clause, this forbid would also block an admin from restoring the document, because forbid wins over every permit. The exception keeps restore open, and the admin permit above decides who may use it.

Schema Definition#

AVP uses a Cedar schema to define your entity types, their attributes, and valid action-entity combinations. The schema is optional but strongly recommended for production. It enables policy validation at creation time, catching typos and structural errors before they reach production.

{
  "SaasApp": {
    "entityTypes": {
      "User": {
        "shape": {
          "type": "Record",
          "attributes": {
            "tenantId": { "type": "String", "required": true },
            "orgRole": { "type": "String", "required": true },
            "tenantTier": { "type": "String", "required": true },
            "email": { "type": "String", "required": false }
          }
        }
      },
      "Document": {
        "shape": {
          "type": "Record",
          "attributes": {
            "tenantId": { "type": "String", "required": true },
            "ownerId": { "type": "String", "required": true },
            "status": { "type": "String", "required": true },
            "sensitivity": { "type": "String", "required": false },
            "sharedWithTenants": {
              "type": "Set",
              "element": { "type": "String" },
              "required": false
            }
          }
        }
      }
    },
    "actions": {
      "ViewDocument": {
        "appliesTo": {
          "principalTypes": ["User"],
          "resourceTypes": ["Document"]
        }
      },
      "EditDocument": {
        "appliesTo": {
          "principalTypes": ["User"],
          "resourceTypes": ["Document"]
        }
      },
      "DeleteDocument": {
        "appliesTo": {
          "principalTypes": ["User"],
          "resourceTypes": ["Document"]
        }
      },
      "RestoreDocument": {
        "appliesTo": {
          "principalTypes": ["User"],
          "resourceTypes": ["Document"]
        }
      },
      "ExportDocument": {
        "appliesTo": {
          "principalTypes": ["User"],
          "resourceTypes": ["Document"]
        }
      }
    }
  }
}

The User attributes match the claims that the trigger adds to the ID token. Because the schema has a namespace, policies name actions in full (SaasApp::Action::"ViewDocument"). Validate every policy against this schema with the Cedar CLI or the Cedar playground before you publish it.

Policy Store Configuration#

A policy store is the container for your Cedar schema, policies, and identity source configuration. Connect the user pool as the identity source, with SaasApp::User as the principal type and the ID token as the token type. The key architectural decision is whether to use one policy store per tenant or a shared policy store for all tenants.

SaaS Multi-Tenant Patterns#

Multi-tenancy is the core challenge in SaaS authorization. The question is how to isolate tenants from each other while keeping the authorization infrastructure manageable.

Pool Model vs. Silo Model#

Silo Model

User Pool
Tenant A

Policy Store
Tenant A

User Pool
Tenant B

Policy Store
Tenant B

Pool Model

Single
User Pool

Shared
Policy Store

Pool model: Single Cognito User Pool with custom:tenantId attribute. Single AVP policy store with tenant-scoped Cedar policies.

  • Simpler to manage and deploy
  • Lower cost (one User Pool, one policy store)
  • Tenant isolation enforced at the Cedar policy level
  • Works for most B2B SaaS products
  • Risk: a policy bug could leak data across tenants

Silo model: Separate User Pool and policy store per tenant.

  • Stronger isolation boundary (infrastructure-level separation)
  • Required for compliance-heavy industries (healthcare, finance, government)
  • Higher operational overhead and cost
  • Each tenant can have customized policies
  • More complex deployment and management

Tip

Start with the pool model. It handles most cases well. Move to silo only when compliance or contractual requirements demand infrastructure-level tenant isolation.

Cedar Policies for Multi-Tenancy#

In the pool model, tenant isolation is entirely policy-driven. Every resource access policy must include a tenant check. Role lists use .contains(): Cedar’s in operator tests entity hierarchy membership, and a set of strings on its right side fails both validation and evaluation.

// Base policy: tenant isolation for document viewing
// Every resource policy must verify tenantId match
permit(
  principal,
  action == SaasApp::Action::"ViewDocument",
  resource is SaasApp::Document
)
when {
  principal.tenantId == resource.tenantId &&
  ["admin", "editor", "viewer"].contains(principal.orgRole)
};

// Editors can modify documents within their tenant
permit(
  principal,
  action == SaasApp::Action::"EditDocument",
  resource is SaasApp::Document
)
when {
  principal.tenantId == resource.tenantId &&
  ["admin", "editor"].contains(principal.orgRole)
};

// Only admins can delete documents
permit(
  principal,
  action == SaasApp::Action::"DeleteDocument",
  resource is SaasApp::Document
)
when {
  principal.tenantId == resource.tenantId &&
  principal.orgRole == "admin"
};

For tier-based feature gating, Cedar policies can check the tenant tier:

// Only enterprise tenants can export documents
permit(
  principal,
  action == SaasApp::Action::"ExportDocument",
  resource is SaasApp::Document
)
when {
  principal.tenantId == resource.tenantId &&
  principal.tenantTier == "enterprise"
};

Cross-Tenant Access#

Some SaaS products need controlled cross-tenant access; a consulting firm working across several client tenants is the common case. Model the share on the document: the owning tenant lists the tenants it shares with, and your API loads that list together with the document. A set-valued claim on the user would need a V2_0 trigger, because V1_0 claims are strings only.

// Allow viewing documents that their owning tenant has explicitly
// shared with the caller's tenant
permit(
  principal,
  action == SaasApp::Action::"ViewDocument",
  resource is SaasApp::Document
)
when {
  resource has sharedWithTenants &&
  resource.sharedWithTenants.contains(principal.tenantId)
};

The has test comes first because sharedWithTenants is optional in the schema; the validator rejects access to an optional attribute without it.

Warning

Cross-tenant policies are powerful and risky. They bypass the standard tenant isolation boundary. Review them carefully and test with dedicated integration tests.

Integration Architecture#

The following diagram shows how Cognito tokens flow through the system to reach AVP for authorization decisions.

Client
App

API
Gateway

Cognito
Authorizer

Lambda
Function

Verified
Permissions

Allow
or Deny

The flow works in two tiers:

  1. API Gateway + Cognito Authorizer (coarse-grained): Validates the JWT token, checks that the user is authenticated and the token is not expired. Rejects unauthenticated requests before they reach Lambda.
  2. Lambda + AVP (fine-grained): Loads the resource from the database and passes the ID token plus the resource entity to AVP. AVP builds the principal from the token, evaluates Cedar policies, and returns allow or deny.

JWT Extraction and Tenant Context#

AVP reads the token on its own. The Lambda still needs the tenant ID for its own database queries, so every query can filter by the token’s tenant as a second line of defense.

// Extract tenant context from a validated Cognito JWT
// API Gateway Cognito Authorizer has already validated the token

import { APIGatewayProxyEventV2WithJWTAuthorizer } from "aws-lambda";

interface TenantContext {
  userId: string;
  tenantId: string;
  orgRole: string;
  tenantTier: string;
  email: string;
}

function extractTenantContext(
  event: APIGatewayProxyEventV2WithJWTAuthorizer
): TenantContext {
  const claims = event.requestContext.authorizer.jwt.claims;

  return {
    userId: claims.sub as string,
    tenantId: claims.tenantId as string,
    orgRole: claims.orgRole as string,
    tenantTier: claims.tenantTier as string,
    email: claims.email as string,
  };
}

IsAuthorized and IsAuthorizedWithToken#

AVP provides two authorization APIs:

  • IsAuthorized: You construct the principal entity yourself. Useful when the caller is a backend service with no user token, or when the principal’s attributes must come from your database.
  • IsAuthorizedWithToken: You pass the raw Cognito ID token. AVP checks its signature and expiry and builds the principal from its claims. This is simpler and safer for user-facing requests.

In both APIs, principal and resource are identifiers only. Attributes such as the document’s tenantId travel in the entities list.

import {
  VerifiedPermissionsClient,
  IsAuthorizedCommand,
  IsAuthorizedWithTokenCommand,
  BatchIsAuthorizedWithTokenCommand,
  type AttributeValue,
  type EntityItem,
} from "@aws-sdk/client-verifiedpermissions";

const avpClient = new VerifiedPermissionsClient({ region: "eu-central-1" });
const POLICY_STORE_ID = "ps-your-store-id";

interface ResourceRef {
  type: string; // "Document"
  id: string;
  attributes: Record<string, AttributeValue>;
}

// Resource attributes travel in `entities`; the resource field is only an identifier
function resourceEntity(resource: ResourceRef): EntityItem {
  return {
    identifier: { entityType: `SaasApp::${resource.type}`, entityId: resource.id },
    attributes: resource.attributes,
  };
}

// Option 1: IsAuthorizedWithToken -- user-facing requests
// AVP verifies the ID token and builds the principal from its claims
async function checkWithToken(
  idToken: string,
  action: string,
  resource: ResourceRef
): Promise<boolean> {
  const response = await avpClient.send(
    new IsAuthorizedWithTokenCommand({
      policyStoreId: POLICY_STORE_ID,
      identityToken: idToken,
      action: { actionType: "SaasApp::Action", actionId: action },
      resource: { entityType: `SaasApp::${resource.type}`, entityId: resource.id },
      entities: { entityList: [resourceEntity(resource)] },
    })
  );
  return response.decision === "ALLOW";
}

// Option 2: IsAuthorized -- you build the principal entity yourself
// For calls without a user token, or when the principal's attributes
// must come from your database instead of token claims
async function checkWithPrincipal(
  principalId: string,
  principalAttributes: Record<string, AttributeValue>,
  action: string,
  resource: ResourceRef
): Promise<boolean> {
  const principal = { entityType: "SaasApp::User", entityId: principalId };
  const response = await avpClient.send(
    new IsAuthorizedCommand({
      policyStoreId: POLICY_STORE_ID,
      principal,
      action: { actionType: "SaasApp::Action", actionId: action },
      resource: { entityType: `SaasApp::${resource.type}`, entityId: resource.id },
      entities: {
        entityList: [
          { identifier: principal, attributes: principalAttributes },
          resourceEntity(resource),
        ],
      },
    })
  );
  return response.decision === "ALLOW";
}

BatchIsAuthorized for UI Rendering#

When rendering a UI with multiple resources (a document list, a dashboard with permission-gated features), one call per check adds one network round trip per check. BatchIsAuthorizedWithToken evaluates up to 30 action and resource pairs for one token in a single call.

The token fixes the principal for the whole batch. The token-less BatchIsAuthorized has a similar constraint: either the principal or the resource must be identical across all requests in the batch.

// Batch authorization for UI rendering
// One ID token fixes the principal; up to 30 action/resource pairs per call
async function checkBatchPermissions(
  idToken: string,
  checks: Array<{ action: string; resource: ResourceRef }>
): Promise<boolean[]> {
  // Each resource entity appears once, even when several checks share it
  const entities = new Map<string, EntityItem>();
  for (const check of checks) {
    entities.set(`${check.resource.type}:${check.resource.id}`, resourceEntity(check.resource));
  }

  const response = await avpClient.send(
    new BatchIsAuthorizedWithTokenCommand({
      policyStoreId: POLICY_STORE_ID,
      identityToken: idToken,
      requests: checks.map((check) => ({
        action: { actionType: "SaasApp::Action", actionId: check.action },
        resource: {
          entityType: `SaasApp::${check.resource.type}`,
          entityId: check.resource.id,
        },
      })),
      entities: { entityList: [...entities.values()] },
    })
  );
  return (response.results ?? []).map((r) => r.decision === "ALLOW");
}

// Usage: what can the current user do with one document?
declare const idToken: string; // the caller's Cognito ID token

const doc1: ResourceRef = {
  type: "Document",
  id: "doc-1",
  attributes: {
    tenantId: { string: "tenant-abc" },
    ownerId: { string: "user-9" },
    status: { string: "active" },
  },
};

const permissions = await checkBatchPermissions(idToken, [
  { action: "ViewDocument", resource: doc1 },
  { action: "EditDocument", resource: doc1 },
  { action: "DeleteDocument", resource: doc1 },
]);
// For an editor in tenant-abc: [true, true, false]

API Middleware Pattern#

A reusable middleware for user requests follows the rule above and calls IsAuthorizedWithToken. API Gateway has already validated the token; AVP validates it again and builds the principal from its claims, so the Lambda never assembles principal attributes by hand. The only entity the Lambda builds is the resource, loaded from your database.

// Middleware: the ID token goes to AVP, the resource comes from your database

import type {
  APIGatewayProxyEventV2WithJWTAuthorizer,
  APIGatewayProxyResultV2,
} from "aws-lambda";

type JwtEvent = APIGatewayProxyEventV2WithJWTAuthorizer;

interface AuthorizationConfig {
  action: string;
  // Load the resource before the check: Cedar policies read its
  // tenantId, ownerId and status, so they must come from your data
  loadResource: (event: JwtEvent) => Promise<ResourceRef | undefined>;
}

// API Gateway accepts the token with or without the "Bearer" prefix
function bearerToken(event: JwtEvent): string | undefined {
  const header = event.headers.authorization ?? event.headers.Authorization;
  return header?.replace(/^Bearer\s+/i, "");
}

function withAuthorization(config: AuthorizationConfig) {
  return function (
    handler: (event: JwtEvent, resource: ResourceRef) => Promise<APIGatewayProxyResultV2>
  ) {
    return async (event: JwtEvent): Promise<APIGatewayProxyResultV2> => {
      const idToken = bearerToken(event);
      if (!idToken) {
        return { statusCode: 401, body: JSON.stringify({ error: "Missing token" }) };
      }

      const resource = await config.loadResource(event);
      if (!resource) {
        return { statusCode: 404, body: JSON.stringify({ error: "Not found" }) };
      }

      const allowed = await checkWithToken(idToken, config.action, resource);
      if (!allowed) {
        // Same 404 as a missing document, so other tenants' IDs don't leak
        return { statusCode: 404, body: JSON.stringify({ error: "Not found" }) };
      }

      return handler(event, resource);
    };
  };
}

// Your data access layer: returns the document with its Cedar attributes
declare function loadDocumentRef(documentId: string): Promise<ResourceRef | undefined>;

// Usage in a Lambda handler
export const getDocument = withAuthorization({
  action: "ViewDocument",
  loadResource: async (event) => {
    const documentId = event.pathParameters?.documentId;
    return documentId ? loadDocumentRef(documentId) : undefined;
  },
})(async (_event, resource) => {
  // Runs only if AVP returned ALLOW
  return { statusCode: 200, body: JSON.stringify({ id: resource.id }) };
});

Role Changes and Token Lifetime#

Claims are fixed when Cognito issues the token. When an admin demotes a user or removes them from a tenant, the old ID token keeps the old orgRole and tenantId until it expires. Cognito ID and access tokens are valid for one hour unless the app client sets another value.

Revocation does not shorten that window for AVP. The IsAuthorizedWithToken reference states that tokens stay usable until they expire and that token revocation has no effect on their validity in the policy store. Cognito’s revocation guide says the same about any JWT library that checks only signature and expiry, and the API Gateway JWT authorizer validates tokens that way.

B2B customers often expect offboarding to cut access at once. Three controls together bound the window:

  1. Short token lifetime. The CDK example above sets ID and access tokens to 15 minutes. The Pre Token Generation trigger runs on every refresh, so a role change reaches the next token.
  2. Stop refreshes at offboarding. Call AdminUserGlobalSignOut, which revokes the user’s refresh, ID and access tokens, or disable the user. The client can no longer get new tokens, and the current ones run out within the lifetime above.
  3. Read the role from your database for sensitive actions. For deleting documents, exporting data, or managing members, build the principal from your own tables with IsAuthorized (checkWithPrincipal above) and leave the token claims out of that decision. The check then reflects a role change on the next request, at the cost of one database read.

The sharing list in the cross-tenant policy works the same way: it comes from your database with each request, so revoking a share takes effect on the next check.

Entra ID Alternative#

For teams in the Microsoft ecosystem, the equivalent pattern uses Microsoft Entra External ID for authentication and a separate authorization layer for fine-grained decisions.

Key Differences#

AspectAWS (Cognito + AVP)Microsoft (Entra + custom authz)
AuthenticationCognito User PoolEntra External ID
Authorization engineAVP with Cedar (managed)No native equivalent; Cerbos, OPA, or custom
Policy languageCedar (core properties proven in Lean)Depends on chosen engine
Tenant isolationCedar policies or separate policy storesApp roles + groups + external PDP
Token enrichmentPre Token Generation Lambda triggerClaims mapping in app registration
Pricing modelPer-MAU (Cognito) + per-request (AVP)Per-MAU (Entra) + external PDP cost
Multi-tenant supportCustom attributes + Cedar policiesMulti-tenant app registration

The critical gap in the Microsoft stack is the absence of a managed fine-grained authorization service. Entra handles authentication and coarse-grained authorization (app roles, group memberships, Conditional Access), but for resource-level decisions like “can user X edit document Y in tenant Z,” you need an external PDP.

In practice, Microsoft-stack teams pair Entra with Cerbos or OPA for fine-grained decisions. The Entra token provides identity context (user ID, roles, groups, tenant ID), and the external PDP evaluates policies using that context plus resource attributes.

// Entra ID token claims fed into Cerbos for fine-grained authorization
// Entra provides identity; Cerbos makes the authorization decision

import { GRPC as Cerbos } from "@cerbos/grpc";

const cerbos = new Cerbos("localhost:3593");

async function checkAccess(
  entraToken: { oid: string; roles: string[]; tid: string; groups: string[] },
  resource: { type: string; id: string; ownerId: string; tenantId: string }
) {
  const decision = await cerbos.checkResource({
    principal: {
      id: entraToken.oid,
      roles: entraToken.roles,
      attr: {
        tenantId: entraToken.tid,
        groups: entraToken.groups,
      },
    },
    resource: {
      kind: resource.type,
      id: resource.id,
      attr: {
        owner: resource.ownerId,
        tenantId: resource.tenantId,
      },
    },
    actions: ["read", "update", "delete"],
  });

  return decision.isAllowed("update");
}

The practical difference is assembly cost. On AWS the identity source, the policy store, and the decision API are configured against each other once. The Microsoft path adds a PDP that you deploy, version, and operate yourself.

Cost Analysis#

AVP Pricing#

Amazon Verified Permissions bills single-authorization APIs, batch-authorization APIs, and policy management APIs on different rate cards. There is no single “flat” rate for every API. See Amazon Verified Permissions Pricing (opens in new tab).

Single authorization (IsAuthorized, IsAuthorizedWithToken): each API call is one metered authorization request at $0.000005 per request ($5 per million).

Batch authorization (BatchIsAuthorized, BatchIsAuthorizedWithToken): each batch API call is metered as one request, regardless of how many checks you include in that call (up to 30). Batch calls use tiered per-call pricing on the published US rate card: $0.00015 per call for the first 40 million batch calls a month, $0.000075 for the next 60 million, and $0.00004 above 100 million.

At the first-tier rate, one batch call costs the same as 30 single calls (30 × $0.000005 = $0.00015), and 30 is also the most checks one batch call can carry. A batch with fewer than 30 checks costs more than sending the same checks one by one. At the higher tiers the break-even drops to 15 and 8 checks. Batching pays off in latency: one round trip replaces many.

The table below applies only when every fine-grained decision maps to one IsAuthorized or IsAuthorizedWithToken call.

Monthly single-auth API callsMonthly AVP cost (single APIs)
1 million$5
10 million$50
100 million$500
1 billion$5,000

Note

If you rely heavily on batch APIs, model cost using the batch tiers above and the average number of checks per batch call. Policy management calls (create, update, list policies, etc.) are billed separately.

Cognito Pricing#

Cognito pricing depends on the tier:

TierFree MAUsPrice per MAU (above free)Key Features
Lite10,000$0.0055 (first tier)Basic auth, custom attributes, ID token customization (V1_0 trigger)
Essentials10,000$0.015Passwordless, managed login, access token customization
Plus0$0.02Threat protection, risk-based auth

Note

Lite user pools created on or before November 22, 2024 keep a higher free tier of 50,000 MAUs.

Total SaaS Auth Cost Example#

For a B2B SaaS product with 5,000 MAUs making an average of 200 API calls per day:

  • Cognito (Lite): Free (under 10,000 MAU threshold). The ID-token setup runs on Lite because its V1_0 trigger customizes only the ID token.
  • AVP: 5,000 users x 200 calls x 30 days = 30 million single authorization API calls/month = $150/month (assuming each call is IsAuthorized or IsAuthorizedWithToken at the single-auth rate)
  • Total: ~$150/month for authentication + fine-grained authorization

At 5,000 MAUs the Essentials plan would also be free, so the plan choice does not move this example. It starts to matter above the free tier. At 50,000 MAUs, Lite costs 40,000 × $0.0055 = $220/month, while Essentials, which the access-token path needs, costs 40,000 × $0.015 = $600/month.

Moving the same checks to batch calls does not lower this bill: at this volume every batch call is billed at the first-tier rate, where even a full batch of 30 checks costs the same as 30 single calls.

A self-hosted engine such as SpiceDB brings its own bill: a cluster, a PostgreSQL database, and engineers on call for both. Price it with your own infrastructure rates before you compare.

Which Endpoints Skip AVP#

Not every API call needs an AVP check. The JWT authorizer already proves who is calling; AVP is needed only when the answer depends on a specific resource. How much AVP volume this removes depends on your endpoint mix, so measure it on your own traffic.

EndpointCheckWhy
GET /me/profileJWT authorizer onlyReads the caller’s own record, keyed by sub from the validated token
GET /me/notificationsJWT authorizer onlyData scoped to the caller
GET /documentsJWT authorizer + tenant filter in the queryThe query filters by the token’s tenantId; batch-check the visible page when actions differ per document
GET /documents/{id}AVP (IsAuthorizedWithToken)Depends on the document’s tenant, status and sharing list
DELETE /documents/{id}AVP (IsAuthorized, role from the database)Destructive action; a demoted user must lose it at once

Common Mistakes#

Over-Scoping Policy Stores#

Creating a separate policy store per microservice leads to policy fragmentation. Authorization decisions that span multiple services become impossible within a single policy store. In most cases, a single policy store per environment (dev, staging, production) is sufficient. Use Cedar namespacing (entity type prefixes) to organize policies logically.

Missing Tenant Isolation in Policies#

The most dangerous mistake in multi-tenant SaaS: writing a permit policy without a tenant check.

// DANGEROUS: no tenant isolation
permit(
  principal,
  action == SaasApp::Action::"ViewDocument",
  resource is SaasApp::Document
)
when {
  ["admin", "editor", "viewer"].contains(principal.orgRole)
};

This policy allows any authenticated user to view any document, regardless of tenant. The fix is straightforward but easy to forget:

// CORRECT: tenant isolation enforced
permit(
  principal,
  action == SaasApp::Action::"ViewDocument",
  resource is SaasApp::Document
)
when {
  principal.tenantId == resource.tenantId &&
  ["admin", "editor", "viewer"].contains(principal.orgRole)
};

Warning

Write a Cedar policy test that explicitly verifies cross-tenant access is denied. Run it in CI/CD. This is your safety net against accidental tenant data leakage.

Token Bloat#

Adding too many claims to Cognito tokens through the Pre Token Generation trigger increases token size. Large tokens add latency to every API call and can exceed size limits. Keep claims to what Cedar policies actually evaluate. If you need additional context for authorization, pass it as resource entity attributes in the AVP request rather than token claims.

Not Using IsAuthorizedWithToken#

Manually extracting JWT claims and constructing principal entities is error-prone. IsAuthorizedWithToken lets AVP verify the token signature and expiry and map the claims to the principal, with less code to maintain. Keep IsAuthorized for calls without a user token and for checks that deliberately read the role from your database.

Ignoring Batch Authorization for UI#

Making individual IsAuthorizedWithToken calls in a loop for UI rendering adds one network round trip per check. BatchIsAuthorizedWithToken evaluates up to 30 checks for the same token in one call. At the first-tier rate it never costs less than the same checks sent one by one. Its gain is the round trips it saves.

Skipping Schema Validation#

Deploying Cedar policies without a schema means typos in attribute names silently fail. A policy checking principal.tenantid (lowercase ‘d’) instead of principal.tenantId will never match, and no error is reported. Enable schema validation to catch these issues at policy creation time.

Conclusion#

The pool model with two-tier checking holds for most B2B SaaS products on AWS. Override it when a contract or a regulator demands infrastructure-level tenant separation, when individual tenants need policies you cannot express in one shared store, or when your permission model is relationship-shaped rather than attribute-shaped.

The key takeaways:

  1. Send the ID token to AVP so tenant claims become principal attributes, and add those claims with a V1_0 Pre Token Generation trigger, which the Lite plan supports.
  2. Start with the pool model (single User Pool, single policy store) and move to silo only when compliance demands it.
  3. Every Cedar policy must include a tenant check in multi-tenant applications. Use .contains() for string sets, and test cross-tenant isolation in CI/CD.
  4. Lock tenant attributes out of every app client’s writeAttributes, keep token lifetimes short, and read the role from your database for sensitive actions.
  5. Use IsAuthorizedWithToken for user-facing requests. Use IsAuthorized for service-to-service calls and database-backed checks.
  6. Use the two-tier pattern (API Gateway for coarse checks, AVP for fine-grained) to control costs and latency.
  7. Use BatchIsAuthorizedWithToken for UI rendering to cut round trips. Below 40 million batch calls a month it never costs less than single calls.

The next post in this series covers SpiceDB vs Auth0 FGA for relationship-based access control, where the authorization model is fundamentally different from the attribute-based approach covered here.

References#

External Authorization Systems

Part 2 of 4

A comprehensive guide to external authorization platforms for distributed systems. Covers platform selection, policy language comparison, cloud-native authorization with AWS, and relationship-based access control with SpiceDB and Auth0 FGA.

Related posts