Federated Identity Pattern
Delegate authentication to external identity providers. A pattern for integrating OAuth2, OIDC, SAML, and SSO across multiple services and organizations.
Overview
The Federated Identity pattern delegates authentication to an external identity provider (IdP) instead of managing credentials inside your application. Users log in through a trusted third party — Google, GitHub, Microsoft Entra ID, Okta — and the application receives a signed token it can verify without ever touching a password.
The immediate win is liability: no password table means no password breaches, no reset flows to maintain, and no credential-stuffing surface. The structural win is single sign-on — one login at the IdP silently authenticates the user across every relying application, which is exactly what enterprises mean when they ask for “SSO” in a procurement checklist.
When to Use
- You don’t want to store or manage user passwords
- Users already have accounts with Google, GitHub, Microsoft, or Okta
- Several applications need single sign-on across an organization
- You must authenticate users from partner organizations without creating local accounts
- Compliance requirements mandate centralized identity management (SOC2, HIPAA)
Federated identity is overkill when your user base is a handful of internal admins, when you operate fully offline, or when regulation forbids third-party processors in the auth path. A simple local login beats a half-configured OIDC integration every time.
It’s also worth knowing what you’re signing up for operationally: token validation adds a network dependency (JWKS fetch), the IdP becomes a hard dependency for logins, and account linking — merging a Google identity with a GitHub one — is your problem, not theirs. None of these are reasons not to federate; they’re the maintenance surface you inherit when you do.
Solution
The examples below implement the full authorization-code flow: redirect to the IdP, exchange the code for tokens, then verify the ID token’s signature against the provider’s published keys.
Python (FastAPI + OAuth2/OIDC)
from fastapi import FastAPI, HTTPException, Depends, Header
from fastapi.responses import RedirectResponse
import httpx
import jwt
import time
app = FastAPI()
GOOGLE_CLIENT_ID = "your-client-id"
GOOGLE_CLIENT_SECRET = "your-client-secret"
GOOGLE_REDIRECT_URI = "http://localhost:8000/auth/callback"
GOOGLE_DISCOVERY = "https://accounts.google.com/.well-known/openid-configuration"
async def get_google_discovery():
async with httpx.AsyncClient() as client:
resp = await client.get(GOOGLE_DISCOVERY)
return resp.json()
async def extract_user(authorization: str = Header(None)):
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Missing token")
token = authorization.split(" ")[1]
discovery = await get_google_discovery()
jwks_client = jwt.PyJWKClient(discovery["jwks_uri"])
try:
signing_key = jwks_client.get_signing_key_from_jwt(token)
decoded = jwt.decode(
token,
signing_key.key,
algorithms=["RS256"],
audience=GOOGLE_CLIENT_ID,
)
return decoded
except jwt.PyJWTError:
raise HTTPException(status_code=401, detail="Invalid token")
@app.get("/auth/login")
async def login():
discovery = await get_google_discovery()
auth_url = (
f"{discovery['authorization_endpoint']}"
f"?client_id={GOOGLE_CLIENT_ID}"
f"&redirect_uri={GOOGLE_REDIRECT_URI}"
f"&response_type=code"
f"&scope=openid email profile"
)
return RedirectResponse(auth_url)
@app.get("/auth/callback")
async def callback(code: str):
discovery = await get_google_discovery()
async with httpx.AsyncClient() as client:
token_resp = await client.post(
discovery["token_endpoint"],
data={
"code": code,
"client_id": GOOGLE_CLIENT_ID,
"client_secret": GOOGLE_CLIENT_SECRET,
"redirect_uri": GOOGLE_REDIRECT_URI,
"grant_type": "authorization_code",
},
)
tokens = token_resp.json()
id_token = tokens.get("id_token")
jwks_client = jwt.PyJWKClient(discovery["jwks_uri"])
signing_key = jwks_client.get_signing_key_from_jwt(id_token)
decoded = jwt.decode(
id_token,
signing_key.key,
algorithms=["RS256"],
audience=GOOGLE_CLIENT_ID,
)
return {
"user": {
"email": decoded["email"],
"name": decoded["name"],
"sub": decoded["sub"],
},
"access_token": tokens["access_token"],
}
@app.get("/protected")
async def protected(user: dict = Depends(extract_user)):
return {"message": f"Hello {user['email']}"}
Watch two details in this version. extract_user is defined before any endpoint that depends on it — referencing it earlier raises NameError at import time, since Depends() evaluates immediately. And both token checks fetch the IdP’s JWKS and validate the signature, issuer audience, and expiry; decoding with verify_signature=False accepts forged tokens.
In production, read the client secret from an environment variable or secrets manager, and cache the discovery document and JWKS instead of fetching them per request.
JavaScript (Express + OIDC)
const express = require("express");
const { auth } = require("express-openid-connect");
const app = express();
app.use(
auth({
issuerBaseURL: "https://accounts.google.com",
baseURL: "http://localhost:3000",
clientID: "your-client-id",
secret: "your-secret-key",
authRequired: false,
auth0Logout: true,
routes: {
login: "/auth/login",
callback: "/auth/callback",
logout: "/auth/logout",
},
})
);
app.get("/", (req, res) => {
if (req.oidc.isAuthenticated()) {
res.json({
user: req.oidc.user,
token: req.oidc.accessToken,
});
} else {
res.json({ message: "Not authenticated. Visit /auth/login" });
}
});
app.get("/profile", (req, res) => {
if (!req.oidc.isAuthenticated()) {
return res.status(401).json({ error: "Unauthorized" });
}
res.json({ user: req.oidc.user });
});
app.listen(3000);
express-openid-connect handles discovery, JWKS validation, the state parameter, and session cookies for you — which is why the middleware version is the right default for Node apps. Rolling your own flow is only worth it when you need custom claim mapping or a non-standard provider.
Java (Spring Security + OAuth2)
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class FederatedIdentityApp {
@GetMapping("/user")
public String user(@AuthenticationPrincipal OidcUser principal) {
if (principal == null) return "Not authenticated";
return "Hello, " + principal.getFullName() + " (" + principal.getEmail() + ")";
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http,
ClientRegistrationRepository repo) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/user").authenticated()
.anyRequest().permitAll()
)
.oauth2Login(oauth -> {})
.logout(logout -> logout
.logoutSuccessHandler(
new OidcClientInitiatedLogoutSuccessHandler(repo)
)
);
return http.build();
}
public static void main(String[] args) {
SpringApplication.run(FederatedIdentityApp.class, args);
}
}
// application.yml:
// spring.security.oauth2.client.registration.google.client-id=xxx
// spring.security.oauth2.client.registration.google.client-secret=xxx
Spring Security wires the whole flow from configuration alone — oauth2Login triggers the redirect-and-callback dance, and OidcClientInitiatedLogoutSuccessHandler propagates logout back to the IdP so the SSO session actually ends.
Explanation
Identity work here is shared by three actors:
- Identity Provider (IdP) — Google, GitHub, Entra ID, Okta. Owns credentials, runs the login flow, signs tokens.
- Relying Party (RP) — that’s your app, the one trusting the IdP’s signatures. It receives tokens and never sees a password.
- Protocols — OAuth2 for authorization (delegated access), OIDC layering authentication on top (ID tokens with user claims), and SAML for enterprise SSO in XML form.
The token flow shown in the diagram has two security checkpoints people skip. First, the state parameter on the outbound redirect must come back identical — that’s your CSRF protection on the login itself. Second, the signature check on the ID token must hit the IdP’s published keys (jwks_uri in the discovery document), not a key you bundled. Skip either and “Login with Google” becomes “Log in as anyone.”
For SSO across several apps, each relying party runs the same flow independently and the IdP’s session does the silent work: the second app redirects to the provider, the provider sees an active session and issues the code without prompting. Your apps never talk to each other about identity — they all just trust the same signer.
One subtlety worth noting: the sub claim is unique per client registration, not globally. Google and most providers issue a different sub for the same human across different client IDs, so keying users on sub alone breaks when you split mobile and web into separate OAuth clients. Combine iss + sub for the primary key and keep a provider-agnostic internal user ID for everything downstream.
Variants
| Variant | Protocol | Use Case |
|---|---|---|
| OAuth2 Authorization Code | OAuth2 | Web apps with server-side token exchange |
| OIDC | OIDC (OAuth2 + ID tokens) | Modern web and mobile apps |
| SAML 2.0 | SAML | Enterprise SSO, legacy systems |
| Client Credentials | OAuth2 | Service-to-service authentication |
| Device Code | OAuth2 | TV, IoT, CLI devices without browser |
Pick OIDC unless a constraint forces otherwise. SAML survives in enterprises where the IdP predates OIDC — typically ADFS or older Entra federation setups — and you’ll inherit it through procurement requirements, not choice. Client Credentials and Device Code aren’t user-login variants at all: one authenticates services, the other bootstraps auth on devices that can’t show a login page.
What Works
- Use OIDC for new applications — standardized ID tokens with user claims, and every major provider supports it
- Store only token references, not passwords — the IdP owns credential storage
- Validate tokens on every request — signature, expiry, issuer, audience; no
verify_signature=Falseshortcuts - Use PKCE for public clients (SPAs, mobile) to prevent authorization code interception
- Implement token refresh — access tokens expire; refresh tokens keep sessions alive
- Map IdP roles to local roles — don’t leak provider-specific role names into business logic
- Handle IdP outage gracefully — cache sessions, keep a degraded read-only mode if the business can tolerate it
- Use discovery endpoints — providers publish their config at
/.well-known/openid-configuration; don’t hardcode endpoints
Common Mistakes
- Skipping signature validation — decoding a JWT without verifying it against the IdP’s JWKS accepts any forged token; this is the single most common federated-auth bug
- No account linking strategy — a user who logs in via Google today and GitHub tomorrow is two identities unless you key on a stable claim (
sub) and link deliberately - Half logout — clearing your session cookie while the IdP session stays alive means the next “log in” silently re-authenticates without a prompt; real logout propagates to the provider
- Ignoring clock skew —
exp/iat/nbfchecks fail on skewed servers; allow leeway or sync NTP before blaming the token - Missing
state/noncevalidation — opens login CSRF and replay attacks on the callback - Requesting every scope —
openid email profileis usually enough; extra scopes raise consent friction and expand your breach blast radius - Trusting unverified claims —
email_verifiedexists for a reason; don’t auto-provision accounts off unverified emails
See Also
- Voucher Pattern — token exchange between security domains, the sibling pattern in this space
- Multi-Tenant Data Isolation — what to do with identity once tenants share your app
- OpenID Connect specification — the normative reference for ID tokens and discovery
- RFC 7636 — PKCE — the extension that makes public clients safe
Companion code: the federated-identity-pattern companion repo has the three implementations as runnable files plus a minimal JWKS verification snippet you can lift into non-Spring projects.
Frequently Asked Questions
What's the difference between OAuth2 and OIDC?
OAuth2 handles authorization, not authentication — it grants access to resources. OIDC sits on top of OAuth2 and adds the identity piece: ID tokens that prove who the user is. Use OIDC when you need authentication, OAuth2 when you need delegated access.
Should I use SAML or OIDC?
OIDC for anything new — it's simpler, JSON-based, and plays well with mobile and SPAs. SAML only when the IdP can't do OIDC, which usually means ADFS-era enterprise deployments.
How do I handle multiple identity providers?
Implement a multi-IdP strategy: let users choose their provider at login, then map every provider to one local user record keyed on the sub claim. Passport.js and Spring Security both support several providers natively; the hard part is the linking UI, not the plumbing.
What are the state and nonce parameters for?
state binds the callback to the login request that started it — without it, an attacker can swap in their own authorization code (login CSRF). nonce does the same job inside the ID token for replay protection. Generate both per request, store them server-side or in a short-lived cookie, and reject mismatches.
How does logout work with federated identity?
Two sessions exist: yours and the IdP's. Deleting your cookie alone leaves the IdP session alive, so the next login redirects and instantly re-authenticates — which users experience as "logout doesn't work." Use the provider's end-session endpoint (OIDC end_session_endpoint in the discovery doc) after clearing local state.
What if the identity provider goes down?
Logins stop — that's the trade-off you accept for outsourcing auth. Existing sessions keep working until tokens expire, so longer-lived sessions plus refresh tokens buy you hours of IdP outage tolerance. If the business can't tolerate a login outage at all, run a break-glass local account for admins.
Related Resources
Voucher Pattern
Validate claims and delegate access using signed vouchers without exposing sensitive data. A security pattern for token-based authorization between services.
RecipeOAuth 2.0 Login
How to implement OAuth 2.0 authentication with Google, GitHub, and other providers. Covers the Authorization Code flow with PKCE, state validation, and refresh tokens.
RecipeNode.js OAuth2 GitHub Login with Express
Implement GitHub OAuth2 login flow in Node.js with Express and Passport
RecipeJWT Authentication
Sign, verify, and refresh JWTs in Python, JavaScript, and Java — access/refresh flows, RS256 key pairs, and token revocation done right.
RecipeImplement SSO with SAML 2.0 (Python, Node.js, Java)
Implement SAML 2.0 single sign-on as a Service Provider: XML signature verification, IdP metadata, and secure sessions in Python, Node.js, and Java.
RecipeImplement Secure Session Management
How to create, validate, and expire user sessions securely using HTTP-only cookies, server-side stores like Redis, and CSRF protection.