TL;DR: This post explores the architectural trade-offs between managed IdPs like Auth0 and Clerk, AWS Cognito, and custom builds for B2B SaaS authentication. It demonstrates how to use the Adapter Pattern in TypeScript and Fastify to abstract your identity provider and prevent expensive vendor lock-in. You will also learn how to handle stateless JWT verification via JWKS and programmatically manage B2B tenants using Clerk's Node SDK.
Key Takeaways
- Implement the Adapter Pattern with a unified
IdentityUserinterface to decouple your application logic from specific vendor SDKs. - Build Fastify middleware to centralize stateless JWT verification and inject a normalized user object into the request context.
- Rely on stateless JWT verification using JWKS in your hot path to avoid expensive database lookups.
- Keep JWT claims lean to prevent HTTP
431 Request Header Fields Too Largeerrors caused by overloading tokens with complex RBAC structures. - Account for the "SAML tax" when evaluating Auth0 and Clerk, as essential B2B features like SCIM and SAML SSO are often gated behind expensive enterprise tiers.
- Use Clerk's backend SDK (
@clerk/backend) to provision B2B organizations from code, and mirror organization IDs in your own database.
The conversation around B2B SaaS authentication usually starts with a simple requirement: "We just need users to log in." Six months later, you find yourself untangling a web of Security Assertion Markup Language (SAML 2.0) connections, multi-tenant Role-Based Access Control (RBAC), System for Cross-domain Identity Management (SCIM) directory syncing, and strict EU data residency compliance.
If you default to a fully managed Identity Provider (IdP) like Auth0 or Clerk, you ship quickly, but per-MAU and per-connection pricing can become a large line item as you grow. AWS Cognito is usually cheaper per user, but B2B features such as tenant-aware tokens are built from Lambda triggers you maintain. Building an OpenID Connect (OIDC) server yourself puts every security fix and protocol edge case on your team.
Architecting a pragmatic authentication strategy in 2026 requires understanding your specific scale trajectory, technical debt tolerance, and enterprise client demands. Let's deconstruct the "Buy vs Build" spectrum, evaluate the hidden constraints of modern IdPs, and look at architectures that keep vendor lock-in manageable.
Abstraction as a Defense Mechanism
Before committing to any identity vendor, you must assume you will eventually outgrow them or their pricing model. Tightly coupling your application code to a vendor's specific SDK (e.g., calling auth0.getUser() throughout your business logic) makes a later migration expensive.
The solution is the Adapter Pattern. By abstracting the IdP behind a unified interface, you centralize token validation, tenant resolution, and permission checks.
// src/lib/auth/IdentityProvider.ts
export interface IdentityUser {
id: string;
email: string;
tenantId: string;
roles: string[];
permissions: string[];
}
export interface IdentityProviderAdapter {
verifySession(token: string): Promise<IdentityUser>;
revokeSession(sessionId: string): Promise<void>;
provisionTenant(tenantName: string): Promise<{ tenantId: string }>;
}
In a Node.js or Next.js API, you implement this adapter as a middleware. This ensures your downstream controllers only interact with your standardized IdentityUser object.
// src/middleware/requireAuth.ts
import { FastifyRequest, FastifyReply } from 'fastify';
import type { IdentityUser } from '../lib/auth/IdentityProvider';
import { ClerkAdapter } from '../lib/auth/ClerkAdapter';
// Extend FastifyRequest to include our custom user type
declare module 'fastify' {
interface FastifyRequest {
user?: IdentityUser;
}
}
// Inject your current provider adapter
const authProvider = new ClerkAdapter();
export async function requireAuth(req: FastifyRequest, reply: FastifyReply) {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return reply.status(401).send({ error: 'Missing authorization header' });
}
try {
const token = authHeader.split(' ')[1];
// The provider adapter validates the JWT signature, issuer, and expiry
const user = await authProvider.verifySession(token);
// Inject normalized user into request context
req.user = user;
} catch (err) {
req.log.error({ err }, 'Token verification failed');
return reply.status(401).send({ error: 'Invalid or expired token' });
}
}
Production Note: Never perform database lookups in your hot path authentication middleware unless absolutely necessary. Rely on stateless JWT verification using JWKS (JSON Web Key Sets), but strictly monitor your token sizes. Overloading JWT claims with complex RBAC structures can result in HTTP
431 Request Header Fields Too Largeerrors.
The True Cost of "Buy": Auth0 and Clerk
Managed solutions like Auth0 (Okta) and Clerk offer strong B2B primitives: organization management, out-of-the-box SAML SSO flows, and rich management APIs.
However, enterprise features such as SAML connections and SCIM directory sync are often priced per connection or limited to higher tiers, so the first enterprise customer can change your identity bill noticeably. This is often called the "SAML tax". Check each vendor's current pricing page for the exact limits before you commit, because these plans change often.
If you choose this route, create tenants from your own code through the vendor's backend API, so tenant creation is part of your signup flow rather than a manual dashboard step.
Here is how you create an Organization (Tenant) with Clerk's backend SDK, making the requesting user its admin:
// src/services/tenantService.ts
import { createClerkClient } from '@clerk/backend';
const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY });
export async function createB2BTenant(companyName: string, adminUserId: string) {
// createdBy makes this user an admin of the new Organization
const organization = await clerk.organizations.createOrganization({
name: companyName,
slug: companyName.toLowerCase().replace(/[^a-z0-9]/g, '-'),
createdBy: adminUserId,
});
// Add more members later with clerk.organizations.createOrganizationMembership()
return organization;
}
While this code is simple, relying on it entirely means your core domain model (Tenants) is now dictated by an external system's availability and latency. For resilience, mirror the Organization ID locally in your primary Postgres database and use webhooks to keep the vendor and your system eventually consistent.
The Pragmatic Middle: AWS Cognito Architectures
For teams already on AWS, AWS Cognito is the main alternative to Auth0 and Clerk. It is typically much cheaper per monthly active user, and it now comes in Lite, Essentials and Plus feature plans.
The tradeoff is that Cognito has no built-in concept of "Organizations." A common way to make tokens tenant-aware is to add tenant claims with a Pre Token Generation Lambda trigger. To customize the access token (not just the ID token), the trigger must use the V2_0 event version, which requires the Essentials or Plus feature plan.
Here is the AWS CDK (TypeScript) infrastructure definition for a User Pool hooked into a custom trigger:
// infrastructure/lib/CognitoStack.ts
import * as cdk from 'aws-cdk-lib';
import * as cognito from 'aws-cdk-lib/aws-cognito';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager';
export class AuthStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const dbSecret = secretsmanager.Secret.fromSecretNameV2(this, 'DbSecret', 'prod/auth/db-url');
const preTokenLambda = new lambda.Function(this, 'PreTokenTrigger', {
runtime: lambda.Runtime.NODEJS_22_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('src/lambdas/pre-token-generation'),
environment: {
// Pass a reference to the secret, never the connection string itself
DB_SECRET_ARN: dbSecret.secretArn,
},
});
dbSecret.grantRead(preTokenLambda);
const userPool = new cognito.UserPool(this, 'B2BUserPool', {
userPoolName: 'SaaS-Production-Pool',
// Access token customization (V2_0 events) needs Essentials or Plus
featurePlan: cognito.FeaturePlan.ESSENTIALS,
selfSignUpEnabled: false, // B2B typically uses invite-only
customAttributes: {
tenantId: new cognito.StringAttribute({ mutable: true }),
},
});
// V2_0 events let the trigger customize both ID and access tokens
userPool.addTrigger(
cognito.UserPoolOperation.PRE_TOKEN_GENERATION_CONFIG,
preTokenLambda,
cognito.LambdaVersion.V2_0,
);
}
}
And the corresponding Lambda function. Note the V2_0 response shape, claimsAndScopeOverrideDetails, which differs from the V1_0 claimsOverrideDetails object:
// src/lambdas/pre-token-generation/index.ts
import { PreTokenGenerationV2TriggerEvent } from 'aws-lambda';
import { getSecret } from '@aws-lambda-powertools/parameters/secrets';
import { Client } from 'pg'; // Bundle with the function (e.g. NodejsFunction/esbuild)
export const handler = async (
event: PreTokenGenerationV2TriggerEvent,
): Promise<PreTokenGenerationV2TriggerEvent> => {
const userId = event.request.userAttributes.sub;
// Cached by Powertools between warm invocations
const connectionString = await getSecret<string>(process.env.DB_SECRET_ARN!);
const client = new Client({ connectionString });
await client.connect();
try {
const res = await client.query(
'SELECT tenant_id, role FROM user_tenant_mapping WHERE user_id = $1',
[userId],
);
if ((res.rowCount ?? 0) === 0) {
throw new Error('User does not belong to a tenant');
}
const tenantClaims = {
tenant_id: res.rows[0].tenant_id,
tenant_role: res.rows[0].role,
};
// V2_0 response shape: separate blocks for the ID and access tokens
event.response = {
claimsAndScopeOverrideDetails: {
idTokenGeneration: { claimsToAddOrOverride: tenantClaims },
accessTokenGeneration: { claimsToAddOrOverride: tenantClaims },
},
};
} finally {
// Always close the connection to prevent connection leaks
await client.end();
}
return event;
};
Warning: This trigger runs on every sign-in and token refresh, so its latency and errors become your login latency and errors. Keep it small, put RDS Proxy in front of the database for connection pooling, and alarm on its error rate. If the tenant mapping rarely changes, storing it in a Cognito custom attribute avoids the database call entirely.
The "Build" Reality: Custom Node.js Identity Providers
Sometimes you cannot rely on a hosted vendor. If your SaaS requires on-premise deployments or strict data-control requirements, first evaluate self-hosted open-source identity servers such as Keycloak or Ory, which already implement OIDC, SAML and MFA. Building your own IdP makes sense only when those do not fit.
In the Node.js ecosystem, the oidc-provider package (often called node-oidc-provider) is the most established library for building an OpenID Connect server and is OpenID Certified. If you need help designing that backend, our backend development and API services cover custom identity work.
Implementing a custom IdP requires mapping OIDC concepts (Clients, Grants, Sessions) to your relational database. Here is a simplified Knex.js adapter snippet bridging oidc-provider to PostgreSQL:
// src/idp/OIDCPostgresAdapter.ts
import { Adapter, AdapterPayload } from 'oidc-provider';
import db from '../db/knex'; // Your Knex instance
export class OIDCPostgresAdapter implements Adapter {
private name: string;
constructor(name: string) {
this.name = name;
}
async upsert(id: string, payload: AdapterPayload, expiresIn: number): Promise<void> {
const expiresAt = expiresIn ? new Date(Date.now() + expiresIn * 1000) : null;
await db('oidc_payloads')
.insert({
id,
type: this.name,
payload: JSON.stringify(payload),
expires_at: expiresAt,
})
.onConflict('id')
.merge();
}
async find(id: string): Promise<AdapterPayload | undefined> {
const result = await db('oidc_payloads').where({ id, type: this.name }).first();
if (!result) return undefined;
// Clean up expired payloads aggressively
if (result.expires_at && result.expires_at < new Date()) {
await this.destroy(id);
return undefined;
}
return typeof result.payload === 'string' ? JSON.parse(result.payload) : result.payload;
}
async destroy(id: string): Promise<void> {
await db('oidc_payloads').where({ id, type: this.name }).delete();
}
// consume(), revokeByGrantId() omitted for brevity
}
Building an IdP means you own the complete lifecycle: password hashing (Argon2id), session invalidation mechanisms, rate-limiting, brute-force protection, and Multi-Factor Authentication (TOTP/WebAuthn). This is not a project for a single sprint; it is a continuing security commitment.
B2B Enterprise Table Stakes: Handling SAML 2.0
If you choose the "Build" route, integrating with your enterprise clients' Active Directory or Entra ID requires supporting SAML 2.0. In Node.js, this is typically handled with @node-saml/node-saml or its Passport wrapper @node-saml/passport-saml (the old unscoped passport-saml package is deprecated).
You must expose an Assertion Consumer Service (ACS) endpoint that receives signed XML payloads from the enterprise IdP, validates the signature against that customer's X.509 certificate, and provisions the user "just-in-time" (JIT). Two details matter for security: resolve the tenant from your own configuration (here, the ACS URL), not from an attribute inside the assertion, and never put the resulting session token in a URL, where it ends up in browser history and logs. Note that @node-saml/node-saml v5 renamed the cert option to idpCert.
// src/api/saml/acs.ts
import { FastifyRequest, FastifyReply } from 'fastify';
import { SAML } from '@node-saml/node-saml';
import { getTenantSamlConfig } from '../../services/tenantSamlConfig';
import { provisionEnterpriseUser } from '../../services/userService';
import { generateInternalSaaSToken } from '../../services/sessionService';
// Route: POST /saml/:tenantId/acs (requires @fastify/formbody and @fastify/cookie)
export async function samlAcsHandler(
req: FastifyRequest<{ Params: { tenantId: string } }>,
reply: FastifyReply,
) {
try {
// The tenant comes from the URL we registered with that customer's IdP,
// and only that tenant's IdP certificate can validate the response.
const tenant = await getTenantSamlConfig(req.params.tenantId);
const saml = new SAML({
callbackUrl: `https://api.yoursaas.com/saml/${tenant.id}/acs`,
entryPoint: tenant.idpSsoUrl, // e.g. https://login.microsoftonline.com/.../saml2
idpCert: tenant.idpCert, // The enterprise customer's signing certificate
issuer: 'urn:yoursaas:sp',
audience: 'urn:yoursaas:sp',
});
const { profile } = await saml.validatePostResponseAsync(req.body as Record<string, string>);
if (!profile?.nameID) throw new Error('Invalid SAML Assertion');
// Never trust a tenant ID asserted inside the SAML response itself
const user = await provisionEnterpriseUser({
email: profile.nameID,
tenantId: tenant.id,
ssoProvider: 'saml',
});
// Issue your session in an HttpOnly cookie, never in a URL
reply.setCookie('session', generateInternalSaaSToken(user), {
httpOnly: true,
secure: true,
sameSite: 'lax',
path: '/',
});
return reply.redirect('https://app.yoursaas.com/');
} catch (error) {
req.log.error({ err: error }, 'SAML ACS error');
return reply.redirect('https://app.yoursaas.com/auth/error');
}
}
Migration Strategies: Escaping Vendor Lock-in
What happens when you decide to move from Auth0 to AWS Cognito? Password hashes (bcrypt, scrypt and similar) are one-way, so nobody can export the plaintext passwords, and Cognito's bulk user import cannot take existing password hashes. Without a migration path, every user would need to reset their password.
The pragmatic architectural pattern for this is Lazy Migration (or Shadow Migration). You configure your new IdP to intercept login requests. If the user isn't found in the new system, a Lambda function forwards the submitted password (over TLS) to the legacy IdP. If the legacy IdP authenticates successfully, Cognito creates the user with that password, so the next login happens entirely in Cognito. The trigger only fires for password flows that send the password to Cognito (USER_PASSWORD_AUTH, ADMIN_USER_PASSWORD_AUTH, or USER_AUTH with a password), not SRP.
Here is a conceptual AWS Cognito User Migration trigger doing exactly this:
// src/lambdas/user-migration/index.ts
import { UserMigrationTriggerEvent } from 'aws-lambda';
import axios from 'axios';
export const handler = async (
event: UserMigrationTriggerEvent,
): Promise<UserMigrationTriggerEvent> => {
if (event.triggerSource === 'UserMigration_Authentication') {
// userName is a top-level field; the password is in event.request
const userName = event.userName;
const { password } = event.request;
try {
// Attempt login against the legacy Identity Provider (e.g. Auth0's
// password grant, which must be enabled for this client)
await axios.post('https://legacy-auth.com/oauth/token', {
grant_type: 'password',
username: userName,
password,
client_id: process.env.LEGACY_CLIENT_ID,
client_secret: process.env.LEGACY_CLIENT_SECRET,
});
} catch {
// axios throws on non-2xx responses
throw new Error('Bad password or user not found');
}
// Success: Cognito creates the user with this password
event.response.userAttributes = {
email: userName,
email_verified: 'true',
};
event.response.finalUserStatus = 'CONFIRMED';
event.response.messageAction = 'SUPPRESS'; // Don't send a welcome email
return event;
}
// UserMigration_ForgotPassword: look the user up in the legacy system
// (no password is sent) and return userAttributes the same way.
throw new Error('User not found in legacy system');
};
This pattern avoids a cut-over window and forced password resets for active users. Users who never log in during the migration period still need a bulk import and a password reset, so plan an end date for the legacy IdP.
Choosing Your Path for 2026
There is no one-size-fits-all answer for B2B authentication. For an early-stage startup, building an OIDC server from scratch is rarely a good use of time: buy Clerk or Auth0, and protect yourself with the Adapter Pattern.
If identity costs are growing faster than revenue and your team is comfortable on AWS, Cognito with a small set of Lambda triggers is a reasonable middle ground. For regulated or on-premise deployments, start with a self-hosted server such as Keycloak, and only build on oidc-provider when you need behavior those products cannot provide.
Whatever path you choose, keep identity behind one interface in your codebase from day one.
Sources
- Amazon Cognito pre token generation Lambda trigger
- Amazon Cognito migrate user Lambda trigger
- @node-saml/node-saml on GitHub
- oidc-provider (panva) on GitHub
- Clerk backend SDK: createOrganization()
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
How can I prevent vendor lock-in when using managed identity providers like Auth0 or Clerk?
You can prevent vendor lock-in by implementing the Adapter Pattern to abstract the Identity Provider (IdP) behind a unified interface. By centralizing token validation and tenant resolution, your application code relies on a standardized user object rather than vendor-specific SDKs. This ensures that migrating to a different provider later requires minimal code changes.
What causes HTTP 431 Request Header Fields Too Large errors in B2B authentication?
This error typically occurs when you overload your JSON Web Tokens (JWTs) with complex Role-Based Access Control (RBAC) structures and excessive custom claims. As the JWT grows to hold many tenant permissions, it exceeds the header size limits of your web server or proxy. To avoid this, keep claims to identifiers such as tenant ID and role, and resolve detailed permissions on the server.
What is the "SAML tax" when evaluating B2B SaaS authentication costs?
The "SAML tax" refers to the extra cost of enterprise features such as SAML SSO and SCIM sync, which managed providers often charge per connection or limit to higher tiers. These platforms are fast to adopt, but the first enterprise customer that needs these integrations can raise your identity bill noticeably, so check current pricing before you commit.
Why shouldn't I just default to AWS Cognito to save on identity costs?
AWS Cognito is usually cheaper per user than premium managed IdPs, but it has no built-in organization model, so tenant handling, invitations and per-tenant SAML setup are things you build with Lambda triggers and your own admin UI. Weigh the subscription savings against that engineering and maintenance work.
