OIDC Session Management — Tracking and Maintaining User Sessions Across Applications
In this tutorial, you will learn about OIDC Session Management. We cover key concepts, practical examples, and best practices to help you master this topic.
OIDC session management defines how the provider tracks authenticated sessions and communicates session state changes to client applications, enabling single sign-on and coordinated logout across multiple applications.
What You'll Learn
- How OIDC manages sessions at the provider level
- How session state changes are communicated to clients
- How to implement session monitoring in your application
Why It Matters
Without OIDC session management, users must log in separately to each application. Even with SSO, logging out of one app leaves the user signed in everywhere else. Session management enables coordinated session tracking and logout across all applications using the same provider.
Real-World Use
A user logs into DodaMail (webmail), DodaDrive (storage), and DodaCalendar through the same OIDC provider. The provider maintains a single session. When the user logs out of DodaMail, the provider notifies DodaDrive and DodaCalendar through session management, logging them out everywhere.
flowchart LR
subgraph Provider
SM["Session Manager"]
S1["Session\nUser: jdoe\nCreated: 10:00\nLast Active: 10:30"]
end
subgraph Apps
A1["DodaMail"]
A2["DodaDrive"]
A3["DodaCalendar"]
end
SM -->|"session_state"| A1
SM -->|"session_state"| A2
SM -->|"session_state"| A3
SM <-->|"check_session_iframe"| A1
SM <-->|"check_session_iframe"| A2
style SM fill:#dbeafe,stroke:#2563eb
style S1 fill:#fef3c7,stroke:#d97706
Session State Value
The OIDC provider returns a session_state value in the authentication response:
// Parse session_state from the callback URL
function parseSessionState() {
const urlParams = new URLSearchParams(
window.location.hash.substring(1)
);
const sessionState = urlParams.get('session_state');
// Format: "hash.client_id.origin"
if (sessionState) {
sessionStorage.setItem('oidc_session_state', sessionState);
}
return sessionState;
}
Check Session Iframe
The provider hosts an iframe that client applications use to check session status:
<!-- Include the session check iframe -->
<iframe id="oidc-session-check"
src="https://accounts.example.com/check_session"
style="display:none">
</iframe>
// Session monitoring via postMessage
function checkSession() {
const iframe = document.getElementById('oidc-session-check');
const sessionState = sessionStorage.getItem('oidc_session_state');
const clientId = 'doda-browser';
iframe.contentWindow.postMessage(
clientId + ' ' + sessionState,
'https://accounts.example.com'
);
}
window.addEventListener('message', function(event) {
if (event.origin !== 'https://accounts.example.com') return;
if (event.data === 'changed') {
console.log('Session changed or ended');
// Redirect to login
window.location.href = '/login';
} else if (event.data === 'unchanged') {
console.log('Session is still active');
}
});
// Poll every 30 seconds
setInterval(checkSession, 30000);
Session State Change Detection
from flask import Flask, session, jsonify
import requests
app = Flask(__name__)
@app.route('/api/session/status')
def session_status():
"""Endpoint called by the frontend to verify session status"""
provider_session = session.get('oidc_session_state')
if not provider_session:
return {"status": "no_session"}, 401
# Verify with the provider if the session is still valid
token_endpoint = "https://accounts.example.com/token"
introspect_response = requests.post(
f"{token_endpoint}/introspect",
auth=(session.get('client_id'), session.get('client_secret')),
data={"token": session.get('access_token')}
)
if introspect_response.json().get('active'):
return {"status": "active", "session_state": provider_session}
else:
session.clear()
return {"status": "expired", "session_state": None}, 401
Common Mistakes
1. Not Implementing Session Monitoring
Without session monitoring, users remain logged in to your app even after logging out of the provider. Always check session status periodically.
2. Trusting Client-Side Session State Alone
The session_state value should be verified with the provider. A client-side check is not sufficient for security decisions.
3. Ignoring postMessage Origin Validation
The check_session_iframe communication uses postMessage. Always validate the origin of incoming messages to prevent cross-origin attacks.
4. Polling Too Frequently
Checking session status every few seconds creates unnecessary load. Every 30-60 seconds is sufficient for most applications.
5. Not Handling Iframe Blocking
Some browsers or ad blockers prevent iframe loading. Provide a fallback that polls the provider's session endpoint directly.
Practice Questions
- What is the purpose of the
session_statevalue? - How does the check session iframe work?
- How often should you poll for session changes?
- What security check is critical with postMessage?
- What happens when the provider session expires?
Answers
- It represents the current session state and is used for SSO session tracking. 2. It receives postMessage queries from client iframes and responds with changed/unchanged. 3. Every 30-60 seconds. 4. Validate the event origin matches the provider's origin. 5. The user must re-authenticate and all applications receive session changed notifications.
Challenge
Build a session management dashboard that monitors multiple OIDC client applications and displays their session states in real-time. Include indicators for active, expired, and changed sessions, with a manual refresh button.
FAQ
Mini Project
Create a session management system with a provider-side session registry, a check_session_iframe endpoint, client-side JavaScript for monitoring, and a dashboard showing all active sessions with force-logout capability.
What's Next
- Learn about RP-initiated logout for application-triggered session termination
- Explore OP-initiated logout for provider-triggered logout notifications
- Continue to front-channel and back-channel logout mechanisms
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro