Skip to content
intermediate Phase 6 · Identity, Authentication, and Authorization

Single Sign-On and Federation

Centralize sign-in with SAML or OIDC across applications and domains.

55m
0 problems
Topic Progress 0%

Single Sign-On and Federation: Core Concepts

Single Sign-On and Federation: Core Concepts

Employees at a typical enterprise use dozens of applications daily — email, CRM, project management, HR systems, internal tools. Without SSO, each application maintains its own user database and login screen. Users juggle dozens of passwords, IT manages dozens of account lifecycles, and when someone leaves the company, deprovisioning requires touching every system individually.

Single Sign-On (SSO) solves this by centralizing authentication: users authenticate once to an Identity Provider (IdP), and the IdP vouches for their identity to Service Providers (SPs) — the applications the user wants to access.

The Actors

  • Identity Provider (IdP) — The system that authenticates users and issues identity assertions (e.g., Okta, Azure AD, Ping Identity)
  • Service Provider (SP) — The application the user wants to access (e.g., Salesforce, Slack, a custom web app)
  • User Agent — The browser or client that mediates the interaction

SAML: The Enterprise Standard

Security Assertion Markup Language (SAML) is an XML-based protocol that has been the enterprise SSO standard for over a decade. It defines three roles:

  1. Principal — The user trying to access a resource
  2. IdP — Authenticates the user and issues a SAML assertion
  3. SP — Consumes the SAML assertion and grants access

SAML Flow (SP-initiated):

User → SP: "I want to access the app"
SP → User: Redirect to IdP with SAMLRequest
User → IdP: Authenticate (password, MFA, etc.)
IdP → User: Redirect back to SP with SAMLResponse (assertion)
User → SP: Present SAMLResponse
SP → User: Access granted

The SAML assertion contains:

  • Subject — Who the assertion is about (the user)
  • Conditions — When the assertion is valid (not before, not after)
  • Audience — Which SP the assertion is intended for
  • Attributes — User properties (email, groups, roles)
  • Signature — The IdP's digital signature proving authenticity

OIDC: The Modern Standard

OpenID Connect (OIDC) is a simpler, JSON-based protocol built on OAuth 2.0. It has largely replaced SAML for new applications, especially consumer-facing and mobile apps.

OIDC Flow (Authorization Code Flow):

User → SP: "I want to access the app"
SP → User: Redirect to IdP with client_id, redirect_uri, scope
User → IdP: Authenticate
IdP → User: Redirect back to SP with authorization code
SP → IdP: Exchange code for ID token + access token (server-to-server)
SP → User: Access granted

The ID token is a JSON Web Token (JWT) containing:

{
  "iss": "https://idp.example.com",
  "sub": "user-12345",
  "aud": "my-app-client-id",
  "exp": 1700000000,
  "iat": 1699996400,
  "email": "alice@example.com",
  "groups": ["engineering", "admins"]
}

OIDC is simpler than SAML because it uses JSON instead of XML, leverages standard OAuth 2.0 flows, and the ID token is a signed JWT that the SP can validate locally without calling the IdP.

SAML vs. OIDC

Feature SAML OIDC
Format XML JSON/JWT
Transport HTTP redirects, POST HTTP redirects, POST
Mobile support Poor Excellent
API access Not designed for this Built on OAuth 2.0
Complexity High Moderate
Best for Enterprise web apps Web, mobile, APIs

Where It Fits

SSO and federation sit at the intersection of authentication and authorization. The IdP authenticates the user and provides identity attributes that the SP uses for authorization decisions. Study Authorization Models first to understand how identity attributes drive access decisions, then move to Account Recovery to understand how users regain access when they lose their credentials.

Single Sign-On and Federation: Practice

Single Sign-On and Federation: Practice

SSO is best understood by implementing a simple flow. The exercises below cover both SAML and OIDC concepts.

Exercise 1: Decode a SAML Assertion

A SAML assertion is base64-encoded XML. Decode and inspect one:

# Decode a SAML response
echo "PHNhbWxwOlJlc3BvbnNl..." | base64 -d | xmllint --format -

You will see XML similar to:

<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
  <saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
    <saml:Subject>
      <saml:NameID>alice@example.com</saml:NameID>
    </saml:Subject>
    <saml:Conditions NotBefore="2024-01-01T00:00:00Z" NotOnOrAfter="2024-01-01T01:00:00Z">
      <saml:AudienceRestriction>
        <saml:Audience>https://app.example.com</saml:Audience>
      </saml:AudienceRestriction>
    </saml:Conditions>
    <saml:AttributeStatement>
      <saml:Attribute Name="email">
        <saml:AttributeValue>alice@example.com</saml:AttributeValue>
      </saml:Attribute>
      <saml:Attribute Name="groups">
        <saml:AttributeValue>engineering</saml:AttributeValue>
      </saml:Attribute>
    </saml:AttributeStatement>
  </saml:Assertion>
</samlp:Response>

Key things to verify:

  • The Audience matches your SP's entity ID
  • The NotBefore and NotOnOrAfter conditions are valid
  • The signature is valid (verify with the IdP's public key)

Exercise 2: Decode an OIDC ID Token

An OIDC ID token is a JWT with three base64url-encoded parts separated by dots:

import base64
import json

def decode_jwt(token):
    parts = token.split('.')
    # Decode header
    header = json.loads(base64.urlsafe_b64decode(parts[0] + '=='))
    # Decode payload
    payload = json.loads(base64.urlsafe_b64decode(parts[1] + '=='))
    return header, payload

# Example ID token
id_token = "eyJhbGciOiJSUzI1NiIs..."
header, payload = decode_jwt(id_token)

print("Header:", json.dumps(header, indent=2))
print("Payload:", json.dumps(payload, indent=2))

The payload contains the user's identity claims: sub (subject), email, groups, exp (expiration), iss (issuer), aud (audience).

Exercise 3: Implement a Simple OIDC Client

from flask import Flask, redirect, request, session
import requests
import secrets

app = Flask(__name__)
app.secret_key = secrets.token_hex(32)

OIDC_CONFIG = {
    'issuer': 'https://idp.example.com',
    'client_id': 'my-app',
    'client_secret': 'my-secret',
    'redirect_uri': 'http://localhost:5000/callback',
    'authorization_endpoint': 'https://idp.example.com/authorize',
    'token_endpoint': 'https://idp.example.com/token',
    'jwks_uri': 'https://idp.example.com/.well-known/jwks.json'
}

@app.route('/login')
def login():
    state = secrets.token_urlsafe(16)
    session['state'] = state
    
    auth_url = (
        f"{OIDC_CONFIG['authorization_endpoint']}?"
        f"response_type=code&"
        f"client_id={OIDC_CONFIG['client_id']}&"
        f"redirect_uri={OIDC_CONFIG['redirect_uri']}&"
        f"scope=openid email profile&"
        f"state={state}"
    )
    return redirect(auth_url)

@app.route('/callback')
def callback():
    # Verify state to prevent CSRF
    if request.args.get('state') != session.get('state'):
        return 'Invalid state', 403
    
    # Exchange authorization code for tokens
    token_response = requests.post(OIDC_CONFIG['token_endpoint'], data={
        'grant_type': 'authorization_code',
        'code': request.args.get('code'),
        'redirect_uri': OIDC_CONFIG['redirect_uri'],
        'client_id': OIDC_CONFIG['client_id'],
        'client_secret': OIDC_CONFIG['client_secret']
    })
    
    tokens = token_response.json()
    # In production, verify the ID token signature using the JWKS
    session['id_token'] = tokens['id_token']
    return 'Login successful'

Check Your Understanding

  • Why does the SP verify the state parameter in the OIDC callback?
  • What is the difference between authentication and authorization in SSO?
  • Why is OIDC preferred over SAML for mobile applications?

Single Sign-On and Federation: Trade-offs and Interviews

Single Sign-On and Federation: Trade-offs and Interviews

SSO delivers significant benefits but also introduces risks. A compromised IdP becomes a single point of compromise for every connected application.

When SSO Is the Wrong Tool

  • High-security environments: In environments where compartmentalization is critical (e.g., military, critical infrastructure), a single authentication event granting access to multiple systems may be unacceptable. Use separate authentication for each security domain.
  • Legacy applications: Applications that cannot support SAML or OIDC (e.g., terminal-based apps, old client-server software) may require a separate login. Use a reverse proxy with SSO integration as a bridge.
  • Third-party access: For external users (customers, partners), federated identity through a customer identity platform (Auth0, Okta Customer Identity) is more appropriate than internal SSO.

Security Risks

  • IdP compromise: If an attacker compromises the IdP, they can authenticate to every connected application. Protect the IdP with strong MFA, monitoring, and least-privilege access.
  • Token theft: If an attacker steals a SAML assertion or OIDC ID token, they can replay it to the SP. Mitigate by using short token lifetimes, audience restrictions, and token binding.
  • Assertion wrapping: In SAML, an attacker can wrap a legitimate assertion inside a malicious one. Validate the assertion structure carefully and verify the signature covers the entire assertion.
  • Logout issues: SSO logout is notoriously difficult. When a user logs out of the IdP, all SP sessions should also be terminated. Implement single logout (SLO) or use short session timeouts.

The Passwordless Future

SSO is evolving toward passwordless authentication. Instead of a password + MFA, users authenticate with biometrics or hardware keys (FIDO2). The IdP handles the authentication and issues a token to the SP. This eliminates the password as a attack vector while maintaining the SSO experience.

How This Comes Up in Interviews

  • "What is the difference between SAML and OIDC?" SAML is XML-based, designed for enterprise web SSO. OIDC is JSON-based, built on OAuth 2.0, and works well for web, mobile, and API access. OIDC is simpler and more modern.
  • "How do you secure an SSO implementation?" Use short token lifetimes, validate audience and issuer claims, verify signatures, implement proper logout (SLO), protect the IdP with strong MFA, and monitor for anomalous authentication patterns.
  • "What happens when the IdP is down?" Users cannot authenticate to any SP. Implement fallback authentication (cached credentials, local accounts) for critical applications, or use a highly available IdP deployment.

Practice Problems

0 / 2 solved

Solution
1. User requests access to the SP. 2. SP generates a SAMLRequest and redirects the user's browser to the IdP. 3. User authenticates to the IdP (password, MFA). 4. IdP generates a SAMLResponse containing a signed assertion with the user's identity. 5. IdP redirects the user's browser back to the SP with the SAMLResponse. 6. SP validates the assertion's signature, checks the audience and conditions, and grants access.

Solution
1) iss (issuer) — must match the expected IdP. 2) aud (audience) — must include the client's client_id. 3) exp (expiration) — token must not be expired. 4) iat (issued at) — token must not be issued in the future. 5) Signature — verify using the IdP's public key from the JWKS endpoint. 6) nonce (if used) — must match the value sent in the authorization request.

Quiz

1. What is the primary benefit of Single Sign-On (SSO)?

Question 1 options

2. What is the main difference between SAML and OIDC?

Question 2 options

3. In OIDC, why does the client verify the 'state' parameter in the callback?

Question 3 options

4. What is the biggest security risk of SSO?

Question 4 options

Flashcards

Question

What are the three actors in SSO?

Answer

Identity Provider (IdP) — authenticates users, Service Provider (SP) — the application being accessed, and User Agent — the browser mediating the interaction.

Question

What is SAML?

Answer

Security Assertion Markup Language — an XML-based protocol for enterprise SSO. The IdP issues a signed SAML assertion containing the user's identity, which the SP validates.

Question

What is OIDC?

Answer

OpenID Connect — a JSON-based protocol built on OAuth 2.0. The IdP issues a JWT ID token containing the user's identity claims, which the SP validates locally.

Question

Why is the state parameter important in OIDC?

Answer

It prevents CSRF attacks by ensuring the callback corresponds to an authorization request the client initiated.

Question

What is the biggest security risk of SSO?

Answer

A compromised Identity Provider becomes a single point of compromise for every connected application.

Revision Notes

Key Takeaways

  • 1. Single sign-on reduces password fatigue and centralizes audit for every application login.
  • 2. SAML and OIDC are the two dominant federation protocols for web SSO.
  • 3. OIDC is simpler and more modern than SAML, using JSON/JWT instead of XML.
  • 4. The state parameter in OIDC prevents CSRF attacks.
  • 5. A compromised IdP is a single point of compromise for all connected applications.

Interview Tips

  • • Explain the SAML and OIDC flows step by step.
  • • Compare SAML and OIDC, discussing when to use each.
  • • Describe the security risks of SSO and how to mitigate them.
  • • Connect SSO to the broader identity landscape: authentication, authorization, and account lifecycle management.

Cheat Sheet

Single Sign-On and Federation Cheat Sheet

Phase: Identity, Authentication, and Authorization | Level: intermediate

Key Concepts:

  • IdP (Identity Provider) — authenticates users
  • SP (Service Provider) — the application being accessed
  • SSO: authenticate once, access multiple applications

SAML:

  • XML-based, enterprise web SSO
  • IdP issues signed SAML assertion
  • SP validates signature, audience, conditions

OIDC:

  • JSON/JWT-based, built on OAuth 2.0
  • IdP issues ID token (JWT)
  • SP validates locally using JWKS
  • Works for web, mobile, APIs

Security:

  • Verify state parameter (CSRF protection)
  • Validate iss, aud, exp claims
  • Short token lifetimes
  • Protect the IdP with strong MFA

Tags: identity, sso

Continue Learning

Before You Start

  • No prerequisites listed.