Prompt
Act like a SaaS security architect and tell me how to secure a multi-tenant app with SSO, RBAC, audit logging, and tenant separation.
Latest observation
Here’s a practical SaaS security architecture for a multi-tenant application with SSO, RBAC, audit logging, and tenant separation.
1) Start with the core security model
Identity
- Use a centralized Identity Provider (IdP) for authentication via SAML 2.0 or OIDC/OAuth2.
- Treat your app as a resource server / service provider.
- Support:
- Enterprise SSO
- MFA enforced by the customer’s IdP or your own policy
- Just-in-time provisioning if needed
- SCIM for user and group provisioning/deprovisioning
Authorization
- Use RBAC as the base model:
- Tenant-level roles: Owner, Admin, Manager, Member, Auditor, etc.
- Resource-scoped roles if needed: project admin, billing admin, read-only.
- Consider RBAC + ABAC for finer control:
- Role + tenant + resource ownership + attributes like department, region, environment.
- Never rely on UI-only authorization; enforce in backend APIs.
Multi-tenancy
- Every request must be evaluated in the context of a tenant boundary.
- Tenant context should be derived from:
- The authenticated user’s membership
- The selected tenant/account/workspace
- The token claims and/or server-side session state
2) Tenant separation principles
Golden rule
A user must never be able to access data outside their tenant unless explicitly allowed by a cross-tenant admin function.
Recommended controls
- Add
tenant_idto every tenant-scoped table. - Enforce tenant isolation at multiple layers:
- Application layer
- Service/API layer
- Database layer
- Storage layer
- Logging/analytics layer
Database isolation options
Choose based on customer size and compliance needs:
-
Shared DB, shared schema
tenant_idcolumn on every row- Cheapest, most common
- Requires strong guardrails
-
Shared DB, separate schema per tenant
- Better isolation
- More operational complexity
-
Separate DB per tenant
- Strongest isolation
- Best for high-compliance / large enterprise tenants
- More expensive and operationally heavy
Recommended baseline
For most SaaS products:
- Start with shared schema + row-level tenant isolation
- Use database row-level security (RLS) if supported
- Add “break glass” operational access with strict auditing
3) SSO design
Authentication flow
- Use OIDC for modern app login where possible.
- For enterprise customers, support SAML as well.
- After successful login:
- Map identity to internal user
- Resolve tenant membership
- Issue your own app session / access token with tenant context
Important SSO controls
- Validate issuer, audience, signature, expiration, nonce/state.
- Pin expected IdP metadata and certificate rollover process.
- Enforce email/domain verification only as a hint, not authorization.
- Handle account linking carefully to prevent takeover:
- Require admin approval or verified domain rules
- Avoid auto-joining tenants based only on email domain unless well controlled
Session security
- Short-lived access tokens
- Refresh token rotation
- Revoke sessions on password reset / deprovisioning / suspicious activity
- Bind session to secure cookies where possible:
HttpOnlySecureSameSite=LaxorStrictdepending on app behavior
4) RBAC design
Model
Define roles at the tenant level first, then optionally at object level.
Example:
- Tenant Owner: full control, billing, security settings, user management
- Tenant Admin: manage users, config, resources
- Editor: create/update domain objects
- Viewer/Auditor: read-only access
- Billing Admin: billing only
Best practices
- Keep permissions as explicit actions, not vague labels.
- Example permission strings:
user:createuser:deleteresource:readresource:updateaudit:readbilling:manage
Enforcement pattern
At the API gateway or service layer:
- Authenticate user
- Resolve tenant
- Load roles/permissions for tenant
- Check action on resource
- Verify resource belongs to tenant
- Proceed or deny
Avoid
- Hardcoding role checks in random UI code
- Assuming “admin” means the same thing everywhere
- Storing permissions only in the client
5) Tenant-aware authorization checks
Every backend request should answer:
- Who is the user?
- Which tenant are they operating in?
- What role/permission do they have in that tenant?
- Does the target resource belong to that tenant?
- Are there extra conditions?
- ownership
- status
- region
- data sensitivity
- approval workflow
Recommended pattern
Use a shared authorization middleware or service that every endpoint must call.
Stronger protection
- Use policy-as-code for authorization:
- OPA/Gatekeeper
- Cedar
- Casbin
- Zanzibar-style relationship-based access control if needed
6) Audit logging
What to log
Log all security-relevant actions:
- Login/logout
- SSO events
- MFA changes
- User creation/deletion
- Role changes
- Permission changes
- Tenant creation/deletion
- Resource access to sensitive records
- API key creation/revocation
- Billing/security setting changes
- Data export/download
- Failed authorization attempts
- Admin impersonation / support access
- SCIM provisioning/deprovisioning
Audit log properties
Each event should include:
- timestamp
- actor user ID
- actor tenant ID
- target resource ID
- target tenant ID
- action
- outcome: success/failure
- source IP / device / user agent
- request ID / correlation ID
- auth method used
- before/after state for sensitive changes
- reason/comment if manual override
Important characteristics
- Immutable or append-only storage
- Tamper-evident controls
- Separate audit log access from product access
- Retention policy aligned with compliance needs
- Export to SIEM / log platform
Do not
- Store audit logs in the same mutable table as app data without controls
- Allow tenants to modify their own audit trails
- Log secrets, tokens, or sensitive personal data in cleartext
7) Tenant isolation in APIs and services
API design
- Tenant context should be explicit:
- Path-based:
/tenants/{tenant_id}/resources - Or derived from session/token with server-side validation
- Path-based:
- Never trust a tenant ID from the client without verifying membership.
Service boundaries
- Every microservice should receive tenant context and enforce it.
- Propagate tenant ID in:
- request context
- tracing metadata
- authz decisions
- Validate tenant context at each hop.
Data access layer
- Centralize tenant filters in repositories/ORM layers.
- Use default scopes or query helpers to prevent accidental cross-tenant queries.
- Add automated tests for tenant escape scenarios.
8) Secure provisioning and deprovisioning
Provisioning
- Prefer SCIM for enterprise lifecycle management.
- Create user membership only after valid IdP assertion or SCIM event.
- Default new users to least privilege.
Deprovisioning
- Immediately disable access on SCIM deprovision or IdP disable.
- Revoke active sessions/tokens.
- Remove privileged role assignments or mark them inactive.
Join/leave workflows
- Tenant admins should control who can join.
- Support invite links only with:
- expiration
- single-use or limited-use
- tenant binding
- audit logs
9) Secrets, keys, and token management
- Store secrets in a managed secrets vault.
- Rotate:
- SSO certificates
- API keys
- signing keys
- database credentials
- Use separate signing keys per environment.
- Prefer asymmetric signing for tokens when possible.
- Never embed tenant-specific secrets in client-side code.
10) Defense in depth controls
Application security
- CSRF protection for cookie-based sessions
- XSS protection with output encoding and CSP
- Input validation everywhere
- File upload scanning if applicable
- Rate limiting and abuse detection
- MFA for privileged actions
Infrastructure
- Network segmentation
- Least privilege IAM
- Separate prod/staging/dev
- Encryption in transit and at rest
- WAF and DDoS protection
- Centralized monitoring and alerting
Data security
- Encrypt sensitive fields where appropriate
- Use key separation for high-value tenants if needed
- Mask sensitive data in logs and UI
- Apply data retention and deletion policies
11) Cross-tenant risks to explicitly design against
Common failure modes:
- Missing
tenant_idfilter in a query - IDOR/BOLA vulnerabilities
- Misconfigured SSO allowing tenant hopping
- Overly broad admin roles
- Support staff access without audit trail
- Export jobs leaking data across tenants
- Shared caches without tenant keys
- Search indexes not partitioned by tenant
- Background jobs processing wrong tenant context
- Webhooks not validated against tenant ownership
Mitigations:
- Tenant-scoped test cases
- Security reviews for every query and endpoint
- Policy engine
- Context propagation discipline
- Segregated caches and queues by tenant or tenant key
12) Operational monitoring and response
Monitor
- Authentication failures
- Privilege escalation attempts
- Unusual access patterns
- Cross-tenant access denials
- Mass export/download behavior
- Admin actions outside normal hours
- Repeated SCIM or SSO failures
Incident response
- Ability to:
- disable a tenant
- revoke all sessions
- lock privileged roles
- rotate signing keys
- freeze data export
- Keep runbooks for tenant breach, compromised IdP, and insider abuse
13) Recommended architecture summary
A strong default setup looks like this:
- SSO via OIDC/SAML
- SCIM for lifecycle management
- Tenant-aware sessions/tokens
- RBAC with explicit permissions
- Backend-enforced authorization
- Database tenant isolation with
tenant_id+ RLS - Immutable audit logging
- Separate tenant context in every service
- Strong session/token revocation
- Continuous monitoring and alerting
14) If you want a pragmatic implementation order
- Add tenant model and membership model
- Enforce
tenant_idon all tenant data - Implement auth middleware with tenant resolution
- Add RBAC permission checks in backend
- Add immutable audit logging
- Integrate OIDC/SAML SSO
- Add SCIM provisioning
- Add database RLS and automated tenant isolation tests
- Add admin/security monitoring and incident controls
If you want, I can turn this into:
- a reference architecture diagram,
- a database schema for tenants/users/roles/audit logs, or
- a step-by-step implementation plan for a specific stack like AWS + Postgres + React + Node/Python.