Session Management

Last Updated: May 19, 2025

This document provides an overview of session management in the Typus Development Framework.

Overview

Typus uses a token-based session management approach with JWT (JSON Web Tokens) instead of traditional server-side sessions. This stateless approach provides better scalability and is well-suited for modern web applications and APIs.

Session Flow Diagram

DatabaseTokenServiceAuthMiddlewareAPIFrontendUserDatabaseTokenServiceAuthMiddlewareAPIFrontendUseralt[Valid Token][Expired Token]Login with credentialsPOST /auth/loginGenerate tokensStore refresh tokenAccess & refresh tokensReturn tokensStore tokensAccess protected resourceRequest with access tokenValidate tokenAttach user to requestProcess requestReturn resourceDisplay resource401 UnauthorizedToken expiredPOST /auth/refresh-tokenVerify refresh tokenCheck token validityDelete used refresh tokenStore new refresh tokenNew access & refresh tokensReturn new tokensRetry request with new tokenLogoutPOST /auth/logoutInvalidate tokensDelete refresh tokensConfirmationLogout successfulRedirect to login page

Token Types

The session management system uses two types of tokens:

Access Token

  • Purpose: Authenticate API requests
  • Format: JWT (JSON Web Token)
  • Contents: User ID, email, roles, and expiration time
  • Storage: Client-side (memory, localStorage, or secure cookie)
  • Expiration: Short-lived (typically 1 hour, configurable)
  • Validation: Verified on each API request

Refresh Token

  • Purpose: Obtain new access tokens without re-authentication
  • Format: Cryptographically secure random string
  • Storage: Server-side in database with user association
  • Expiration: Long-lived (typically 7 days, configurable)
  • Usage: Single-use (invalidated after use)
  • Security: Protected against token theft with database validation

Session Lifecycle

1. Session Creation

When a user successfully authenticates:

  1. System generates an access token containing user identity and permissions
  2. System generates a unique refresh token
  3. Refresh token is stored in the database with:
    • User association
    • Expiration timestamp
    • Unique identifier
  4. Both tokens are returned to the client

2. Session Validation

For each protected API request:

  1. Client includes access token in Authorization header
  2. AuthMiddleware extracts and verifies the token
  3. If valid, user information is attached to the request
  4. If invalid or expired, 401 Unauthorized response is returned

3. Session Renewal

When an access token expires:

  1. Client uses refresh token to request new tokens
  2. System validates the refresh token against the database
  3. If valid, the used refresh token is invalidated
  4. New access and refresh tokens are generated
  5. New refresh token is stored in the database
  6. Both new tokens are returned to the client

4. Session Termination

Sessions can be terminated in several ways:

  1. User Logout: All refresh tokens for the user are invalidated
  2. Token Expiration: Access and refresh tokens naturally expire
  3. Manual Invalidation: Administrators can force-terminate sessions
  4. Security Events: Password changes or suspicious activity triggers session invalidation

Security Considerations

Token Security

  1. JWT Secret: Access tokens are signed with a secure secret key
  2. Token Storage:
    • Access tokens should be stored in memory when possible
    • Refresh tokens should use secure HTTP-only cookies or secure storage
  3. HTTPS: All token transmission must occur over HTTPS

Protection Against Common Attacks

  1. Token Theft: Refresh tokens are single-use and tied to user accounts
  2. XSS Protection: Proper token storage mitigates cross-site scripting risks
  3. CSRF Protection: Token-based auth is naturally resistant to CSRF
  4. Token Replay: JTI (JWT ID) ensures tokens cannot be replayed

Session Management Best Practices

  1. Short-lived Access Tokens: Minimize the impact of token compromise
  2. Token Rotation: Refresh tokens are rotated with each use
  3. Concurrent Sessions: Multiple devices can maintain independent sessions
  4. Session Monitoring: Failed token attempts are logged for security monitoring

Frontend Session Handling

The frontend application manages sessions through:

  1. Token Storage: Securely storing tokens (memory for access, secure storage for refresh)
  2. Automatic Renewal: Transparently refreshing expired tokens
  3. Auth State Management: Maintaining authentication state across the application
  4. Logout Handling: Clearing tokens and auth state on logout
Backend APIAPI ClientAuth StoreApplicationBackend APIAPI ClientAuth StoreApplicationalt[Not Authenticated][Token Expired][Token Valid]Check authenticationNot authenticatedRedirect to loginRefresh token requestPOST /auth/refresh-tokenNew tokensUpdate tokensAuthentication validAuthentication validMake API requestRequest with tokenResponseData

Session Configuration

The session management system is configurable through environment variables:

  • JWT_SECRET: Secret key for signing JWTs
  • JWT_EXPIRY: Access token expiration time (default: 1h)
  • REFRESH_TOKEN_EXPIRY: Refresh token expiration time (default: 7d)

Conclusion

The token-based session management system in Typus provides a secure, scalable approach to authentication and authorization. By separating short-lived access tokens from long-lived refresh tokens, the system balances security and user experience while maintaining stateless API architecture.

WARNING

Failed to fetch dynamically imported module: https://typus.dev/assets/RecursiveNavItem-Cep7andh.js

{ "stack": "AppError: Failed to fetch dynamically imported module: https://typus.dev/assets/RecursiveNavItem-Cep7andh.js\n at https://typus.dev/assets/index-DS79FI73.js:315:420\n at dn (https://typus.dev/assets/vue-vendor-Ct83yDeK.js:13:1385)\n at We (https://typus.dev/assets/vue-vendor-Ct83yDeK.js:13:1455)\n at Ws.t.__weh.t.__weh (https://typus.dev/assets/vue-vendor-Ct83yDeK.js:14:7364)\n at jt (https://typus.dev/assets/vue-vendor-Ct83yDeK.js:13:1866)\n at v (https://typus.dev/assets/vue-vendor-Ct83yDeK.js:14:4019)\n at https://typus.dev/assets/vue-vendor-Ct83yDeK.js:14:4097" }