Understanding PBC authorization
A practical reference for custom PBC development and authorization debugging.
Explains how the Gateway passes x-context headers, how RLS enforces
database tenant isolation, and how to resolve common 401/403 auth errors.
Understanding the architecture overview
uses a multi-layered authentication and authorization architecture across all (s).
The primary architectural layers include:
- Browser / Client Layer: Contains the React Tooling Shell (Admin UI)
passing Auth0 JWT (
id_token) as a Bearer token, and Storefront Applications (B2C / B2B) passing a signed,httpOnlycommerce_user_tokencookie. - Federated Gateway (Router): An Apollo-compatible federated router running
as a sidecar container. It receives authentication credentials, forwards
requests to subgraphs, injects required context headers
(
x-context,x-account-id,x-user-id,x-org-id), and composes responses from multiple subgraphs. - PBC Subgraphs & Data Layer: Individual subgraphs (Identity, Catalog, Pricing, etc.) backed by with Row-Level Security (RLS) enforcement.
Key principles of this architecture include:
- Auth0 is the Identity Provider (IdP) that handles user authentication using OAuth 2.0 / OpenID Connect (OIDC).
- The Identity owns the user lifecycle, session management, and context resolution.
- The Federated Gateway routes GraphQL operations to the correct subgraphs.
- The
x-contextHTTP header (Base64-encoded JSON) carries authenticated user identity claims to every downstream . - Row-Level Security (RLS) acts as the authoritative access-control enforcement layer rather than application code.
Routing requests with the Federated Gateway
utilizes GraphQL Federation 2 with an Apollo-compatible router deployed as a sidecar container alongside each subgraph.
Gateway Helm Configuration Example
# Helm chart configuration (common-helmchart/values.yaml)
sidecar:
enabled: true # Deploy federated router as sidecar
sidecarImage:
repository: myacr.azurecr.io/federated-router
tag: "latest"
Client Configuration
All clients send GraphQL operations to a single relative endpoint (/graphql). Local development proxies and deployed web proxies forward requests to the federated router:
// Shell configuration (appConfig.ts)
const GATEWAY_GRAPHQL_URL = '/graphql'; // Relative path — no CORS
export const appConfig = {
graphqlGatewayUrl: GATEWAY_GRAPHQL_URL,
identityServiceUrl: GATEWAY_GRAPHQL_URL,
workspaceServiceUrl: GATEWAY_GRAPHQL_URL,
workflowServiceUrl: GATEWAY_GRAPHQL_URL,
};
Subgraph Registration using Database Smart Comments
Subgraphs expose schema annotations using smart comments on data tables:
COMMENT ON TABLE app_public.user_account IS
E'@federation key(user_id)\n@federation shareable';
The AutoFederationPlugin in each
performs the following tasks:
- Discovers
@federationsmart comments defined in the database. - Generates federation schema fields including
_service,_entities, and_Entityunion types. - Registers entity DataLoader factories to enable cross-subgraph data fetching.
Enforcing authorization via the X-Context header
Every enforces boundary authorization using the
Base64-encoded x-context HTTP header.
Decoded X-Context JSON Structure
{
"accountId": "t1abc123xyz4567890123",
"userId": "u1abc123xyz4567890123",
"activeOrgId": "o1abc123xyz4567890123",
"eligibleOrgIds": ["o1abc123xyz4567890123"],
"personaIds": ["persguestuser00000001"],
"workspaceIds": ["ws_abc123xyz456789012"],
"activeContractId": "ct_abc123xyz456789012",
"eligibleContractIds": ["ct_abc123xyz456789012"],
"segmentIds": ["sg_abc123xyz456789012"],
"activeLocale": "en-US",
"activeCurrency": "USD",
"userType": "b2b",
"sessionType": "registered",
"version": 1
}
Fastify PreHandler Header Validation Pipeline
- Checks if the operation is a
resolveContextmutation. If true, fast-tracks the request. - Checks for schema introspection/federation queries in production environments. If detected, rejects request with 401 Unauthorized.
- Validates the presence of the
x-contextheader. Rejects with 401 if missing. - Validates that
x-contextcontains valid Base64 string formatting. - Validates required JSON fields (
accountId,userId,activeOrgId) formatted as 21-character NanoIDs. - Validates format of supplementary headers (
x-account-id,x-user-id,x-org-id). - Performs cross-tenant validation. If input
accountIddoes not matchx-contextaccountId, rejects with 403 Forbidden. - Applies query governance checks (complexity, depth limits). Rejects with 400 Bad Request if limits are exceeded.
- Passes validation, sets RLS session variables, and executes query.
Enforcing database security using PostgreSQL Row-Level Security (RLS)
RLS provides authoritative data isolation independently of application code logic.
Setting Session Context
Prior to executing queries, PostGraphile sets database session parameters from
the validated x-context values:
SET LOCAL app.account_id = 't1abc123xyz4567890123'; SET LOCAL app.user_id = 'u1abc123xyz4567890123'; SET LOCAL app.workspace_id = 'ws_abc123xyz456789012';
RLS Policy Definitions Example
-- Layer 1: Tenant isolation (enforced across all tables) CREATE POLICY account_isolation ON app_public.user_account USING (account_id = current_setting('app.account_id', true)); -- Layer 2: Permission-based write control CREATE POLICY write_control ON app_public.user_account FOR INSERT USING (app_public.has_permission('identity:admin'));
Handling authentication and authorization errors
The system returns specific HTTP error responses based on validation failure conditions:
| Category | Condition | Returned Error Message / Action |
|---|---|---|
| 401 Unauthorized | Missing x-context header |
Unauthorized: x-context header is
required |
| 401 Unauthorized | Invalid Base64 string in header | Unauthorized: x-context header contains invalid base64
characters |
| 401 Unauthorized | Invalid NanoID format | Invalid format. Expected a 21-character
NanoID |
| 403 Forbidden | accountId tenant mismatch |
Forbidden: The accountId provided in the request does not
match your authenticated account |
| 403 Forbidden | RLS policy violation | You do not have permission to perform this
action |
| Session Error | Expired or tampered session cookie | SESSION_INVALID response with
clearCookie directive |
Appendix — HTTP header reference
Inbound Request Headers to PBC Subgraphs
| Header | Format | Required? | Source |
|---|---|---|---|
x-context |
Base64 JSON string | Yes (Except resolveContext) |
Gateway from Identity response |
x-account-id |
21-character NanoID | Conditional | Gateway |
x-user-id |
21-character NanoID | Conditional | Gateway |
x-org-id |
21-character NanoID | Conditional | Gateway |
x-workspace-id |
NanoID or empty | No | Shell fetch interceptor |
x-host-name |
FQDN String | No | Shell fetch interceptor |
Authorization |
Bearer <jwt> |
Phase 1 only | Shell (Stripped post-resolution) |