TL;DR: A purpose-built identity platform can handle sign-in, session handling, token issuance, and key rotation for a server while protecting endpoints with a sealed cookie session and FastAPI dependency injection, according to WorkOS. The practical lesson is that application teams should stop treating auth as custom code and govern it as an identity control plane boundary.
At a glance
What this is: This is a tutorial on securing a FastAPI API with delegated authentication, with the key finding that session-based auth and token validation can be offloaded from application code.
Why it matters: It matters because IAM, PAM, and application security teams must decide where identity responsibilities belong when APIs, service accounts, and future AI clients all depend on the same trust boundary.
👉 Read WorkOS's FastAPI authentication tutorial for the full integration walkthrough
Context
FastAPI authentication is not just a code pattern, it is a governance boundary. Once an API exposes protected endpoints, teams must decide whether sign-in, session state, and token validation live in application logic or in a delegated identity layer that can be governed consistently across environments.
This tutorial sits in the human identity lane today, but the architectural lesson reaches further. The same boundary choices shape how teams will later govern machine-to-machine access and AI clients, because the trust decision happens before the request reaches business logic.
Key questions
Q: How should security teams secure FastAPI endpoints without writing custom auth logic?
A: Use a delegated identity provider for sign-in, session issuance, and token validation, then enforce authentication through FastAPI dependencies on every protected route. That keeps application code focused on business logic while making auth behavior consistent, reviewable, and easier to revoke or rotate centrally.
Q: Why do sealed sessions and cookie-based auth still need careful governance?
A: Sealed sessions reduce browser exposure, but they do not eliminate trust in session lifecycle, cookie password handling, or server-side validation. Teams still need clear ownership for revocation, expiry, rotation, and error handling, because the security boundary has simply moved rather than disappeared.
Q: What breaks when a protected FastAPI route is missing the auth dependency?
A: The endpoint becomes reachable without the session check that should have blocked unauthenticated access. In practice, this creates route drift, where a single missed dependency can expose user data or writes even though the rest of the application appears properly secured.
Q: Which frameworks are relevant when governing delegated application authentication?
A: NIST Cybersecurity Framework 2.0 is relevant for access governance and protective controls, while zero trust architecture helps teams think about continuous verification at the request boundary. For human identity, NIST SP 800-63 remains useful for federation and authentication assurance choices.
Technical breakdown
Authorization code flow and sealed sessions in FastAPI
The tutorial uses the OAuth 2.0 authorization code flow to move the user from a hosted sign-in page back to the application with a short-lived code. The server exchanges that code for a session and stores a sealed session cookie, meaning the browser never handles raw refresh-token material. Cookie sealing reduces exposure, but it does not remove the need to trust the session lifecycle, the cookie password, or the server-side validation path that rehydrates the session on each request.
Practical implication: keep session creation, sealing, and validation outside endpoint code and treat them as controlled identity services.
Dependency injection as an access control gate
FastAPI’s Depends() mechanism turns authentication into a reusable precondition. The dependency runs before the endpoint handler, loads the sealed session, authenticates it, and either injects the user context or stops the request with a 401. That pattern keeps protected routes clean, but it also means the security property depends entirely on the dependency being attached to every sensitive route. One missing dependency turns a protected resource back into a public one.
Practical implication: inventory every route and verify that the auth dependency is attached to each protected path, not just the obvious ones.
JWT verification, JWKS rotation, and browser cookie trust
The article highlights the pieces teams usually underestimate: JWT verification, JWKS rotation, session management, and secure cookie storage. Each component is simple in isolation, but together they create a trust chain that spans the browser, the API server, and the identity provider. The real architectural issue is not whether the framework can parse a token, but whether the application can continuously prove that the session is still valid, bound to the right user, and resistant to replay or theft.
Practical implication: validate the full trust chain, not just the token format, and test rotation and invalidation paths as part of release readiness.
Breaches seen in the wild
- Salesloft OAuth token breach — hackers stole OAuth tokens to access Salesforce data via Salesloft.
- Internet Archive breach — unsecured GitLab authentication tokens exposed 31M Internet Archive accounts.
Read our 52 NHI Breaches Analysis report for a comprehensive view of breaches impacting Non-Human Identities including AI Agents.
NHI Mgmt Group analysis
Delegating authentication to a hosted identity platform changes the control boundary, not just the implementation detail. The tutorial is framed as developer convenience, but the deeper governance effect is that session issuance, key rotation, and cookie sealing move out of the app and into a managed identity control plane. That matters because IAM teams can now review a smaller local attack surface, but only if they also govern the external auth dependency as part of the application’s trust architecture. The practitioner implication is that auth ownership becomes a shared operational boundary, not a code snippet.
Cookie-sealed sessions create identity state that is harder to inspect but easier to govern centrally. Sealing session data before it reaches the browser reduces local exposure, yet it also shifts trust toward the platform that seals and later reloads that session. This is a useful pattern for human authentication, but it should be understood as managed session state rather than a magic security layer. The practitioner implication is to treat sealed sessions as a governed asset with explicit lifecycle and revocation assumptions.
The named concept here is identity control-plane delegation: the application stops performing authentication logic itself and instead depends on an external service for sign-in, session creation, and token lifecycle management. That model reduces code burden, but it also concentrates failure modes in the identity layer and the dependency boundary. For IAM and security architects, the implication is that resilience, logging, and recovery must be designed around the delegated control plane, not only around the API runtime.
This pattern is human IAM today, but it is already a template for machine access tomorrow. The article’s mention of MCP clients and machine-to-machine auth shows how the same application can later serve humans, services, and AI clients through different identity paths. That is why identity architecture should be evaluated as a cross-actor governance model rather than a single login feature. The practitioner implication is to design for multiple actor types before the application grows into them.
FastAPI dependency-based protection is only as strong as route discipline and review discipline. A protected endpoint is protected because the auth dependency is present, not because the framework is inherently safe. In practice, the governance gap is route drift, where a new endpoint ships without the required dependency or with a weaker path. The practitioner implication is to make auth dependency coverage part of code review, policy checks, and release validation.
From our research:
- Organisations maintain an average of 6 distinct secrets manager instances, creating fragmentation that undermines centralised control, according to The State of Secrets in AppSec.
- Only 44% of developers are reported to follow security best practices for secrets management, exposing a significant developer behaviour gap.
- That fragmentation makes lifecycle-focused governance more valuable, so start with Ultimate Guide to NHIs , Lifecycle Processes for Managing NHIs and then map the auth boundary back to application routes.
What this signals
Identity control-plane delegation: FastAPI teams are increasingly moving authentication decisions out of code and into external services, which changes where reviewers should look for failure. The application may be smaller, but the security boundary is wider because the auth service, cookie lifecycle, and route-level enforcement now form one trust chain.
For programmes that already govern service accounts and API keys, the same logic applies here: if the identity decision sits outside the app, then lifecycle, revocation, and logging must also sit outside ad hoc code review. Use the Ultimate Guide to NHIs , Standards and NIST Cybersecurity Framework 2.0 to anchor those controls in a repeatable model.
For practitioners
- Map auth ownership to a control boundary Document where sign-in, session issuance, token validation, and key rotation live. Treat the identity platform as part of the application’s security architecture, not as a helper library, and assign explicit owners for validation, revocation, and incident response.
- Verify dependency coverage on every protected route Review each FastAPI endpoint and confirm that the authentication dependency is attached wherever data access, mutation, or user context is involved. Add automated checks so new routes cannot be merged without the dependency in place.
- Test session invalidation and rotation paths Exercise logout, expiry, cookie deletion, and signing key rotation in staging before production release. Confirm that a sealed session cannot be replayed after revocation and that failed validation produces a hard denial rather than a permissive fallback.
- Separate public health checks from user data paths Keep endpoints like /health unauthenticated only when they expose no sensitive context, and ensure every route that returns per-user state or accepts writes is locked behind session validation.
- Prepare the same pattern for M2M and AI clients If the API will later be called by services or MCP clients, define distinct identity flows now so human sessions are not overloaded as the default trust model. Keep actor type, credential type, and authorization boundary explicit from the start.
Key takeaways
- Delegated authentication reduces custom code, but it also turns the identity provider into part of the application’s trust boundary.
- FastAPI dependency injection makes route protection straightforward, yet a single missing dependency can still reopen access to sensitive data.
- Teams should govern session lifecycle, route coverage, and future machine-access paths together, because the same pattern will eventually serve more than human users.
Standards & Framework Alignment
This section maps relevant standards and security frameworks to the operational risks and controls described in this guidance.
NIST CSF 2.0, NIST Zero Trust (SP 800-207) and NIST SP 800-63 set the governance and control requirements practitioners need to meet.
| Framework | Control / Reference | Relevance |
|---|---|---|
| NIST CSF 2.0 | PR.AC-1 | Directly maps to authentication decisions at the application boundary. |
| NIST Zero Trust (SP 800-207) | PR.AC-4 | Continuous verification fits request-by-request session validation. |
| NIST SP 800-63 | IAL2 | Useful for federated human sign-in and identity assurance decisions. |
Use assurance-aligned federation choices when external identity providers handle login.
Key terms
- Delegated Authentication: Delegated authentication is the practice of outsourcing sign-in, session creation, and related credential handling to an external identity service. The application still enforces access, but the trusted identity workflow lives outside the codebase, which changes where security reviews, logging, and revocation need to focus.
- Sealed Session: A sealed session is encrypted session state stored by the application in a browser cookie in a form that cannot be read or altered without the server-side secret. It preserves user continuity while reducing exposure of raw session material, but it still depends on correct validation, rotation, and expiry handling.
- Auth Dependency: An auth dependency is a reusable access check that FastAPI runs before an endpoint handler executes. It can block unauthenticated requests, inject verified user context, and centralise session validation, but it only works when every protected route actually uses it consistently.
- Identity Control Plane: An identity control plane is the system that issues, validates, rotates, and revokes identity state across applications and actors. In this pattern, it becomes the authoritative layer for trust decisions, so outages, misconfiguration, or weak lifecycle governance can affect every consuming app.
Deepen your knowledge
FastAPI authentication patterns, session governance, and delegated identity design are core topics in our NHI Foundation Level course, the industry's only accredited NHI security programme. If you are extending application auth into machine or AI access, it is worth exploring.
This post draws on content published by WorkOS: Securing a FastAPI Server with WorkOS AuthKit. Read the original.
Published by the NHIMG editorial team on 2026-03-20.
NHI Mgmt Group — the independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org