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.
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.tenantIdandprincipal.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_0event can add claims to the ID token, and the Lite plan includes that event version. Adding claims to the access token needs aV2_0event, 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 tocustom: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#
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.
The flow works in two tiers:
- 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.
- 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:
- 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.
- 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. - 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(checkWithPrincipalabove) 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#
| Aspect | AWS (Cognito + AVP) | Microsoft (Entra + custom authz) |
|---|---|---|
| Authentication | Cognito User Pool | Entra External ID |
| Authorization engine | AVP with Cedar (managed) | No native equivalent; Cerbos, OPA, or custom |
| Policy language | Cedar (core properties proven in Lean) | Depends on chosen engine |
| Tenant isolation | Cedar policies or separate policy stores | App roles + groups + external PDP |
| Token enrichment | Pre Token Generation Lambda trigger | Claims mapping in app registration |
| Pricing model | Per-MAU (Cognito) + per-request (AVP) | Per-MAU (Entra) + external PDP cost |
| Multi-tenant support | Custom attributes + Cedar policies | Multi-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 calls | Monthly 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:
| Tier | Free MAUs | Price per MAU (above free) | Key Features |
|---|---|---|---|
| Lite | 10,000 | $0.0055 (first tier) | Basic auth, custom attributes, ID token customization (V1_0 trigger) |
| Essentials | 10,000 | $0.015 | Passwordless, managed login, access token customization |
| Plus | 0 | $0.02 | Threat 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_0trigger 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
IsAuthorizedorIsAuthorizedWithTokenat 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.
| Endpoint | Check | Why |
|---|---|---|
GET /me/profile | JWT authorizer only | Reads the caller’s own record, keyed by sub from the validated token |
GET /me/notifications | JWT authorizer only | Data scoped to the caller |
GET /documents | JWT authorizer + tenant filter in the query | The 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:
- Send the ID token to AVP so tenant claims become principal attributes, and add those claims with a
V1_0Pre Token Generation trigger, which the Lite plan supports. - Start with the pool model (single User Pool, single policy store) and move to silo only when compliance demands it.
- 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. - Lock tenant attributes out of every app client’s
writeAttributes, keep token lifetimes short, and read the role from your database for sensitive actions. - Use IsAuthorizedWithToken for user-facing requests. Use IsAuthorized for service-to-service calls and database-backed checks.
- Use the two-tier pattern (API Gateway for coarse checks, AVP for fine-grained) to control costs and latency.
- 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#
- Amazon Verified Permissions Documentation (opens in new tab) - Official guide to AVP concepts, schema definition, and policy evaluation
- Mapping Amazon Cognito Tokens to Schema (opens in new tab) - How AVP maps ID token claims to principal attributes and access token claims to context, and why the token type is an early decision
- Cedar Policy Language Documentation (opens in new tab) - Official Cedar language reference, grammar specification, and policy writing guides
- Cedar Operators (opens in new tab) - The
inhierarchy operator,.contains()for set membership, and thehasattribute test - Cedar Lean Formalization (opens in new tab) - The properties of Cedar’s authorizer and type checker that are proven in Lean
- Amazon Verified Permissions Policy Store Schema (opens in new tab) - Schema definition for entity types, attributes, and action-entity mappings
- Working with Amazon Cognito Identity Sources (opens in new tab) - Configuring Cognito as an identity source for AVP
- IsAuthorizedWithToken API Reference (opens in new tab) - Token-based authorization requests, the
entitiesparameter, and token validity after revocation - Pre Token Generation Lambda Trigger (opens in new tab) - Event versions per feature plan, ID token claim customization, and trigger sources including token refresh
- Working with User Attributes (opens in new tab) - Custom attribute mutability and app client read and write permissions
- Ending User Sessions with Token Revocation (opens in new tab) - RevokeToken, GlobalSignOut, AdminUserGlobalSignOut, and how revoked JWTs behave in other verifiers
- CreateUserPoolClient API Reference (opens in new tab) - Default one-hour ID and access token validity and the WriteAttributes setting
- Control Access to HTTP APIs with JWT Authorizers (opens in new tab) - How API Gateway validates JWTs, audiences, and route scopes
- Cognito Multi-Tenant Application Best Practices (opens in new tab) - AWS guidance on multi-tenancy patterns with Cognito
- Custom-Attribute Multi-Tenancy Best Practices (opens in new tab) - Using custom attributes for tenant isolation in Cognito
- Amazon Verified Permissions Pricing (opens in new tab) - Rate cards for single authorization, batch authorization, and policy management APIs
- Amazon Cognito Pricing (opens in new tab) - Cognito pricing tiers (Lite, Essentials, Plus) and which tier includes access token customization
- Microsoft Entra External ID Overview (opens in new tab) - Microsoft’s customer-facing identity platform replacing Azure AD B2C
External Authorization Systems
Part 2 of 4A 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.
All posts in this series
Related posts
A vendor-neutral evaluation of AWS Verified Permissions, Cedar, OpenFGA, SpiceDB, Cerbos, and OPA: deployment, consistency, cost drivers, and a decision tree.
authorization · security · architecture +4
Add multi-tenant isolation to your permission system, evaluate CASL as a library alternative, and use decision frameworks to choose the right authorization architecture.
typescript · nextjs · authorization +3
A Cognito passkey migration guide for SaaS teams on email, password, and SMS OTP: configuration, enrollment, and the four-tier recovery ladder that replaces SMS.
authentication · security · aws +2
A deep comparison of Cedar, Rego, OpenFGA DSL, and Cerbos YAML/CEL policy languages: syntax, performance, formal verification, tooling, and TypeScript integration.
authorization · security · architecture +2
SpiceDB vs Auth0 FGA (OpenFGA): when ZedTokens, self-hosting or AuthZed's managed SpiceDB beat the default, plus list queries, outbox sync and pricing.
authorization · security · architecture +3