Session Management
The IAM service maintains server-side session records for every authenticated user. Sessions track device information, geographic location, activity timestamps, and token bindings. They provide the foundation for concurrent session limits, device management, and the administrative impersonation feature.
Session Architecture
Each login creates a UserSession entity that persists for the lifetime of the refresh token. Sessions are managed by the SessionService and exposed through the SessionController.
Session Entity
| Field | Type | Description |
|---|---|---|
id | Long | Auto-generated primary key |
userId | Long | The owning user |
tokenId | String | The JTI of the associated access token |
refreshTokenId | String | The JTI of the associated refresh token |
ipAddress | String | Client IP at session creation |
userAgent | String | Raw user agent string |
deviceType | String | Parsed device type (Desktop, Mobile, Tablet) |
browser | String | Parsed browser name and version |
operatingSystem | String | Parsed OS name and version |
location | String | Geo-resolved location (city, country) |
createdAt | Instant | Session creation timestamp |
lastActivityAt | Instant | Last request timestamp |
expiresAt | Instant | Session expiration (matches refresh token TTL) |
active | Boolean | Whether the session is currently valid |
revokedAt | Instant | Timestamp of revocation (if revoked) |
revokeReason | String | Reason for revocation |
Session Lifecycle
Login / Register
|
v
Create Session
(IP, user agent, device fingerprint)
|
v
Session Active
(updated on each authenticated request)
|
+--- Token Refresh ---> Update session token binding
|
+--- Timeout ---------> Mark inactive
|
+--- User Logout -----> Revoke session
|
+--- Admin Revoke ----> Revoke with reason
|
+--- Lockout ---------. Revoke all sessions
|
v
Session EndedSession API Endpoints
The SessionController exposes the following endpoints under /api/v1/sessions:
List Active Sessions
GET /api/v1/sessions
Authorization: Bearer {access_token}Returns all active sessions for the authenticated user. The current session is flagged:
[
{
"id": 101,
"deviceType": "Desktop",
"browser": "Chrome 121",
"operatingSystem": "macOS 14.3",
"location": "San Francisco, US",
"ipAddress": "203.0.113.42",
"createdAt": "2026-02-12T08:00:00Z",
"lastActivityAt": "2026-02-12T10:30:00Z",
"current": true
},
{
"id": 98,
"deviceType": "Mobile",
"browser": "Safari 17",
"operatingSystem": "iOS 17.3",
"location": "San Francisco, US",
"ipAddress": "203.0.113.50",
"createdAt": "2026-02-11T20:15:00Z",
"lastActivityAt": "2026-02-12T09:45:00Z",
"current": false
}
]List All Sessions (Including Inactive)
GET /api/v1/sessions/all
Authorization: Bearer {access_token}Returns all sessions, including those that have expired or been revoked. Useful for security auditing.
Get Session Count
GET /api/v1/sessions/count
Authorization: Bearer {access_token}{
"count": 3
}Revoke a Specific Session
DELETE /api/v1/sessions/{sessionId}
Authorization: Bearer {access_token}Returns 204 No Content. The session is marked as inactive and any associated refresh tokens are invalidated.
Revoke All Other Sessions
DELETE /api/v1/sessions/others
Authorization: Bearer {access_token}Revokes all sessions except the current one. Returns the count of revoked sessions:
{
"revoked": 2
}This is commonly used when a user suspects unauthorized access -- they can terminate all other sessions while keeping their current session active.
Revoke All Sessions
DELETE /api/v1/sessions/all
Authorization: Bearer {access_token}Revokes all sessions including the current one. The user will need to re-authenticate:
{
"revoked": 3
}Device Management
The DeviceFingerprintService tracks recognized devices for each user. Device fingerprints are collected from client-side signals and used by the risk assessment engine.
Device Entity
| Field | Type | Description |
|---|---|---|
id | Long | Auto-generated primary key |
userId | Long | The owning user |
fingerprint | String | Hashed device fingerprint |
name | String | User-assigned device name |
deviceType | String | Desktop, Mobile, Tablet |
browser | String | Browser name and version |
operatingSystem | String | OS name and version |
trusted | Boolean | Whether the device is explicitly trusted |
firstSeenAt | Instant | When the device was first observed |
lastSeenAt | Instant | Most recent login from this device |
loginCount | Integer | Number of logins from this device |
Device Controller Endpoints
| Method | Endpoint | Description |
|---|---|---|
GET | /api/v1/devices | List all registered devices |
GET | /api/v1/devices/{id} | Get device details |
PUT | /api/v1/devices/{id}/trust | Mark a device as trusted |
PUT | /api/v1/devices/{id}/untrust | Remove trust from a device |
PUT | /api/v1/devices/{id}/name | Rename a device |
DELETE | /api/v1/devices/{id} | Remove a device |
DELETE | /api/v1/devices | Remove all devices |
Device Trust and Risk Assessment
Trusted devices reduce the risk score during login:
| Device Status | Risk Impact |
|---|---|
| Trusted device, known IP | -0.2 risk score reduction |
| Known device (not trusted), known IP | No adjustment |
| Known device, new IP | +0.1 risk score increase |
| Unknown device, known IP | +0.2 risk score increase |
| Unknown device, unknown IP | +0.4 risk score increase |
| Unknown device, TOR/VPN IP | +0.6 risk score increase |
Concurrent Session Limits
The IAM service enforces configurable limits on the number of concurrent sessions per user:
| Tier | Default Limit | Behavior on Exceed |
|---|---|---|
| Free | 3 | Oldest session is automatically revoked |
| Professional | 10 | Oldest session is automatically revoked |
| Enterprise | Unlimited | No limit |
The limit is checked during session creation. If the user has reached their limit, the oldest active session is revoked to make room for the new one.
Admin Impersonation
The impersonation feature allows platform administrators to act as another user for troubleshooting purposes. Every impersonation action is fully audited.
Start Impersonation
POST /api/v1/impersonation/start
Authorization: Bearer {admin_token}
Content-Type: application/json{
"targetUserId": 42,
"reason": "Investigating dashboard rendering issue reported in SUPPORT-12345",
"ticketReference": "SUPPORT-12345"
}Requirements:
| Requirement | Details |
|---|---|
| Permission | users:impersonate or ADMIN role |
| Reason | Minimum 10 characters |
| Ticket reference | Optional but recommended |
| Target restrictions | Cannot impersonate other admins or super-admins |
| Max concurrent sessions | 3 per admin |
Response:
{
"sessionId": "imp_a1b2c3d4e5f6",
"token": "eyJhbGciOiJIUzI1NiIs...",
"targetUser": {
"id": 42,
"email": "target.user@acme.com",
"roles": ["ANALYST"]
},
"expiresAt": "2026-02-12T12:00:00Z"
}The returned token is an impersonation token (see Token Lifecycle) that the admin uses for subsequent requests.
End Impersonation
POST /api/v1/impersonation/{sessionId}/end
Authorization: Bearer {admin_token}Returns 204 No Content. The impersonation token is invalidated.
Record Actions
During an impersonation session, significant actions are recorded for the audit trail:
POST /api/v1/impersonation/sessions/{sessionId}/record-action
Content-Type: application/json{
"action": "Viewed dashboard 'Revenue Overview' (id: 15)"
}Audit History
GET /api/v1/impersonation/audit?page=0&size=20
Authorization: Bearer {admin_token}Returns paginated impersonation history for the tenant, including session details, actions performed, and duration.
Force End Session (Admin)
POST /api/v1/impersonation/sessions/{sessionId}/force-end
Authorization: Bearer {admin_token}Allows a super-admin to force-end another admin's impersonation session. Requires the ADMIN role.
Impersonation Statistics
GET /api/v1/impersonation/stats
Authorization: Bearer {admin_token}{
"activeSessions": 1,
"totalSessionsLast30Days": 15,
"averageDurationMinutes": 12,
"topImpersonators": [
{ "email": "admin@matih.ai", "count": 8 }
]
}Zero-Trust Session Evaluation
The ZeroTrustSecurityService continuously evaluates session risk beyond the initial login. Sessions can be re-evaluated at any time based on behavioral signals:
| Trigger | Evaluation |
|---|---|
| IP address change mid-session | Re-check geo-location consistency |
| Access to sensitive resource | Elevate authentication requirement |
| Long idle period | Require re-authentication |
| Unusual API call pattern | Flag for review |
| Cross-tenant access attempt | Block and alert |
When a session fails re-evaluation, the service can:
- Require step-up authentication (re-enter password or MFA)
- Reduce session scope (read-only mode)
- Terminate the session immediately
Session Cleanup
Expired and revoked sessions are cleaned up by a scheduled task:
@Scheduled(cron = "0 0 2 * * *") // Daily at 2 AM
public void cleanupExpiredSessions() {
int deleted = sessionService.deleteExpiredSessions(
Instant.now().minus(Duration.ofDays(30))
);
log.info("Cleaned up {} expired sessions", deleted);
}Sessions are retained for 30 days after expiration for audit purposes before being permanently deleted.
Next Steps
- API Reference -- complete endpoint catalog
- Tenant Lifecycle -- how sessions relate to tenant provisioning
- API Gateway -- session validation at the edge