MATIH Platform is in active MVP development. Documentation reflects current implementation status.
6. Identity & Access Management
Session Management

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

FieldTypeDescription
idLongAuto-generated primary key
userIdLongThe owning user
tokenIdStringThe JTI of the associated access token
refreshTokenIdStringThe JTI of the associated refresh token
ipAddressStringClient IP at session creation
userAgentStringRaw user agent string
deviceTypeStringParsed device type (Desktop, Mobile, Tablet)
browserStringParsed browser name and version
operatingSystemStringParsed OS name and version
locationStringGeo-resolved location (city, country)
createdAtInstantSession creation timestamp
lastActivityAtInstantLast request timestamp
expiresAtInstantSession expiration (matches refresh token TTL)
activeBooleanWhether the session is currently valid
revokedAtInstantTimestamp of revocation (if revoked)
revokeReasonStringReason 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 Ended

Session 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

FieldTypeDescription
idLongAuto-generated primary key
userIdLongThe owning user
fingerprintStringHashed device fingerprint
nameStringUser-assigned device name
deviceTypeStringDesktop, Mobile, Tablet
browserStringBrowser name and version
operatingSystemStringOS name and version
trustedBooleanWhether the device is explicitly trusted
firstSeenAtInstantWhen the device was first observed
lastSeenAtInstantMost recent login from this device
loginCountIntegerNumber of logins from this device

Device Controller Endpoints

MethodEndpointDescription
GET/api/v1/devicesList all registered devices
GET/api/v1/devices/{id}Get device details
PUT/api/v1/devices/{id}/trustMark a device as trusted
PUT/api/v1/devices/{id}/untrustRemove trust from a device
PUT/api/v1/devices/{id}/nameRename a device
DELETE/api/v1/devices/{id}Remove a device
DELETE/api/v1/devicesRemove all devices

Device Trust and Risk Assessment

Trusted devices reduce the risk score during login:

Device StatusRisk Impact
Trusted device, known IP-0.2 risk score reduction
Known device (not trusted), known IPNo 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:

TierDefault LimitBehavior on Exceed
Free3Oldest session is automatically revoked
Professional10Oldest session is automatically revoked
EnterpriseUnlimitedNo 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:

RequirementDetails
Permissionusers:impersonate or ADMIN role
ReasonMinimum 10 characters
Ticket referenceOptional but recommended
Target restrictionsCannot impersonate other admins or super-admins
Max concurrent sessions3 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:

TriggerEvaluation
IP address change mid-sessionRe-check geo-location consistency
Access to sensitive resourceElevate authentication requirement
Long idle periodRequire re-authentication
Unusual API call patternFlag for review
Cross-tenant access attemptBlock and alert

When a session fails re-evaluation, the service can:

  1. Require step-up authentication (re-enter password or MFA)
  2. Reduce session scope (read-only mode)
  3. 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