Authentication Flow
This document describes the complete authentication flow architecture implemented in the CIVITAS Core v2 platform using modern OAuth2/OIDC standards with Keycloak as the identity provider.
Overview
The authentication system implements a secure OAuth2/OIDC flow with Keycloak integration, JWT-based session management, and comprehensive route protection. The architecture follows security-by-design principles and provides a seamless user experience across the platform.
JWT Token Architecture
The system employs two distinct types of JWT tokens that serve different purposes:
- Keycloak JWT Access Token: The actual access token issued by Keycloak, used for authenticating API calls to backend services. This JWT contains user claims and permissions for resource access.
- NextAuth Session JWT: A separate JWT created by NextAuth that wraps the Keycloak tokens (access_token, refresh_token) plus session metadata. This JWT is stored in the HTTP-only session cookie for browser session management.
When making API calls, the Keycloak access token is extracted from the NextAuth session JWT and used for authentication.
Authentication Flow Sequence Diagram
Flow Description
1. Initial Access Attempt
When a user attempts to access a protected resource, the platform's middleware layer intercepts the request and validates the user's authentication status. If no valid session exists, the user is automatically redirected to the login interface, ensuring that protected resources remain secure while providing a smooth user experience.
2. Login Initiation
The login interface presents users with authentication options, prominently featuring Keycloak integration. This centralized approach ensures consistent authentication across all platform components and leverages identity management capabilities.
3. OAuth2/OIDC Flow
The platform implements the standard OAuth2 Authorization Code flow with OIDC extensions, providing robust security through:
- Authorization Code Exchange: Prevents token exposure in browser history
- State Parameter Validation: Protects against CSRF attacks
- PKCE Support: Enhances security for public clients
- Scope-based Access Control: Enables fine-grained permission management
4. Token Exchange and Management
Upon successful authentication, the system securely exchanges the authorization code for access tokens, refresh tokens, and identity tokens. This server-to-server communication ensures that sensitive credentials never traverse the client-side environment.
5. Session Architecture
The platform employs a hybrid session management approach:
- JWT-based Storage: Enables stateless authentication and horizontal scaling
- Secure Cookie Delivery: HTTP-only, secure cookies prevent XSS attacks
- Token Encapsulation: NextAuth embeds access and refresh tokens in its own signed JWT payload, which is then stored in an HTTP-only cookie
Token Refresh Mechanism
The system uses an event-based token refresh approach where tokens are refreshed when the jwt() callback is invoked during requests. When an access token expires, the JWT callback triggers a refresh request to Keycloak's token endpoint. After successful token refresh, NextAuth re-issues the session cookie with the updated token to maintain session continuity. If the refresh fails, the session receives a "RefreshTokenError" and the user must re-authenticate.
Additionally, given the platform's short token timeout (1-5 minutes), client-side polling (refetchInterval in SessionProvider) proactively triggers refresh requests before expiration to prevent session interruptions. This polling mechanism includes refresh attempt limits that reset on user interactions, extending token validity as long as the page remains active.
6. Route Protection and Access Control
A comprehensive middleware system ensures that:
- All protected routes require valid authentication
- Public endpoints remain accessible without authentication
- Session validation occurs transparently for each request
- Invalid or expired sessions trigger automatic re-authentication
7. Ongoing Session Management
Authenticated users enjoy seamless access to protected resources through persistent session cookies. The system validates sessions on each request while maintaining optimal performance through efficient token validation mechanisms.
Key Components
Middleware Layer
The middleware component intercepts all requests and applies authentication policies. It handles route protection by distinguishing between public paths (login, API authentication endpoints) and protected routes that require valid user sessions. The middleware applies authentication to all routes except API endpoints, static assets, images, and files with extensions.
Authorization Logic
The system implements authorization checks that verify user authentication status and determine access permissions. When users are not authenticated, they are redirected to the login interface, while authenticated users can access protected resources.
JWT Token Management
The platform uses JWT callbacks to handle token lifecycle:
- Stores access tokens, refresh tokens, and expiration information within JWT payloads
- Manages token persistence and retrieval for session validation
- Handles token-based authentication across requests
- Session maximum age: 30 days
- Token expiration check includes 60-second buffer before actual expiry
- Access tokens are refreshed automatically when expired
Session Management
Session handling creates and maintains user sessions by:
- Exposing access tokens to client applications when needed
- Managing secure HTTP-only cookie storage
- Coordinating session creation with JWT token management