Skip to main content

Session Management in the Production Environment

This guide explains how to manage sessions when working with the FinHub API in the Production environment, which implements enterprise-grade session handling for live financial transactions.

Session Tokens Overview

When a user logs in through the authentication endpoints, the system creates a session and returns several tokens:
{
  "expires_in": 1800,
  "token_type": "Bearer",
  "scope": "01f0418c-36da-17a0-830a-aca6bf25e007",
  "customerId": "12345678-abcd-1234-efgh-1234567890ab",
  "tenantId": "1234567",
  "userSessionToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Key Session Components

ComponentDescriptionUsage
userSessionTokenJWT token for user session validationUsed for session validation and contains user identity claims
refreshTokenToken used to obtain a new session token without re-authenticationUsed when the session token expires
customerIdUnique identifier for the customerReference in customer-related operations
tenantIdIdentifier for the tenantUsed for multi-tenant operations

Required Session Headers

Every API request in the FinHub Production environment must include these headers:
HeaderDescriptionRequiredExample
AuthorizationBearer token for authenticationYesBearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
X-Activity-IDUUID that identifies a specific user activity or flowYes550e8400-e29b-41d4-a716-446655440000
X-Tenant-IDTenant identifier for multi-tenant operationsYes1234567
X-Request-IDUnique identifier for each request for traceabilityYes123e4567-e89b-12d3-a456-426614174000
X-Session-IDSession identifier for session trackingYessession-12345678
X-Correlation-IDIdentifier for request correlation across servicesYescorr-12345678

Request ID Generation

The Request ID should be a UUID (v4) generated for each individual API request:
  • Tab
  • Tab
  • Tab
// Generate a random UUID v4 for each request
const requestId = crypto.randomUUID();

Enterprise Session Lifecycle Management

Session Creation

A session is created when a user successfully authenticates through the login endpoint. The session includes:
  1. A user session token (JWT)
  2. A refresh token for token renewal
  3. An internally managed access token (not exposed to clients)
  4. User identity information

Proactive Token Refresh

In the Production environment, you must implement proactive token refresh to prevent session expiration:
  • Tab
// Example of proactive token refresh
class TokenManager {
  constructor() {
    this.userSessionToken = null;
    this.refreshToken = null;
    this.tokenExpiry = 0;
    this.refreshThreshold = 300; // Refresh 5 minutes before expiration
    this.refreshInProgress = false;
    this.refreshInterval = null;
  }
  
  setTokens(userSessionToken, refreshToken, expiresIn) {
    this.userSessionToken = userSessionToken;
    this.refreshToken = refreshToken;
    this.tokenExpiry = Date.now() + (expiresIn * 1000);
    
    // Set up automatic refresh
    this.setupRefreshInterval();
  }
  
  setupRefreshInterval() {
    // Clear any existing interval
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
    }
    
    // Calculate time until refresh (expiry minus threshold)
    const timeUntilRefresh = Math.max(0, (this.tokenExpiry - Date.now()) - (this.refreshThreshold * 1000));
    
    // Set timeout to refresh the token
    setTimeout(() => this.refreshTokenIfNeeded(), timeUntilRefresh);
  }
  
  async refreshTokenIfNeeded() {
    // Check if token needs refresh and not already in progress
    if (this.shouldRefreshToken() && !this.refreshInProgress) {
      try {
        this.refreshInProgress = true;
        await this.performTokenRefresh();
      } catch (error) {
        console.error('Token refresh failed:', error);
        // Implement retry logic or redirect to login
      } finally {
        this.refreshInProgress = false;
      }
    }
  }
  
  shouldRefreshToken() {
    // Check if token will expire within the threshold
    return this.tokenExpiry - Date.now() < (this.refreshThreshold * 1000);
  }
  
  async performTokenRefresh() {
    const tenantId = localStorage.getItem('tenantId');
    const requestId = crypto.randomUUID();
    
    const response = await fetch('https://api.finhub.cloud/api/v2.1/auth/token/refresh', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Tenant-ID': tenantId,
        'X-Request-ID': requestId
      },
      body: JSON.stringify({
        refreshToken: this.refreshToken,
        customerId: 'OQ1GG9iFxVcgzforkJR8CImHiuwa',
        customerSecret: 'lPGwgaAENdwLxtfuqQu5R606jswa'
      })
    });
    
    if (!response.ok) {
      throw new Error(`Token refresh failed: ${response.status}`);
    }
    
    const refreshData = await response.json();
    
    // Update stored tokens
    this.setTokens(
      refreshData.userSessionToken,
      refreshData.refreshToken,
      refreshData.expires_in
    );
    
    // Update secure storage
    localStorage.setItem('userSessionToken', refreshData.userSessionToken);
    localStorage.setItem('refreshToken', refreshData.refreshToken);
    localStorage.setItem('tokenExpiry', this.tokenExpiry);
    
    return refreshData.userSessionToken;
  }
  
  getValidToken() {
    // Check if token needs immediate refresh
    if (this.shouldRefreshToken()) {
      this.refreshTokenIfNeeded();
    }
    return this.userSessionToken;
  }
}

// Usage
const tokenManager = new TokenManager();

// After authentication
tokenManager.setTokens(
  authData.userSessionToken,
  authData.refreshToken,
  authData.expires_in
);

// When making API requests
const token = tokenManager.getValidToken();

Session Monitoring and Auditing

In the Production environment, you must implement session monitoring and auditing:
  1. Log Session Events: Log all session-related events (creation, refresh, expiration, termination)
  2. Monitor Session Activity: Monitor for unusual session activity patterns
  3. Implement Session Limits: Enforce concurrent session limits per user
  4. Track Session Metrics: Track session duration, activity, and geographic location

Session Termination

To explicitly terminate a session, call the logout endpoint:
POST /api/v2.1/auth/logout HTTP/1.1
Host: api.finhub.cloud
Content-Type: application/json
X-Tenant-ID: 1234567
X-Activity-ID: 550e8400-e29b-41d4-a716-446655440000
X-Request-ID: 123e4567-e89b-12d3-a456-426614174000
X-Session-Active: true
X-User-Session-Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
  • Tab
async function logout() {
  const userSessionToken = localStorage.getItem('userSessionToken');
  const tenantId = localStorage.getItem('tenantId');
  const activityId = localStorage.getItem('activityId');
  const requestId = crypto.randomUUID();
  
  try {
    // Call logout endpoint
    const response = await fetch('https://api.finhub.cloud/api/v2.1/auth/logout', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${userSessionToken}`,
        'Content-Type': 'application/json',
        'X-Tenant-ID': tenantId,
        'X-Activity-ID': activityId,
        'X-Request-ID': requestId
      }
    });
    
    // Log logout result
    if (response.ok) {
      console.log('Logout successful');
    } else {
      console.error('Logout failed:', response.status);
    }
  } catch (error) {
    console.error('Logout error:', error);
  } finally {
    // Clear all session data regardless of logout API success
    secureSessionStorage.clear();
    
    // Redirect to login page
    window.location.href = '/login';
  }
}

Enterprise Security Best Practices

Secure Token Storage

Store tokens securely using enterprise-grade security measures:
PlatformRecommended StorageImplementation
Web BrowserHttpOnly cookies with SameSite=StrictUse a secure cookie library with proper flags
Mobile AppsSecure Keychain (iOS), Keystore (Android)Use platform-specific secure storage APIs
Server-sideHardware Security Module (HSM)Use HSM integration for token storage

Token Transmission Security

  • Use TLS 1.3 for all API communications
  • Implement certificate pinning for mobile and desktop applications
  • Use secure headers (HSTS, X-Content-Type-Options, etc.)
  • Implement network-level encryption for all communications

Session Anomaly Detection

Implement session anomaly detection to identify potential security threats:
  1. Unusual Locations: Monitor for session access from unusual geographic locations
  2. Concurrent Sessions: Detect multiple concurrent sessions for the same user
  3. Unusual Activity Patterns: Monitor for unusual API call patterns
  4. Time-based Anomalies: Monitor for access during unusual hours

Disaster Recovery

Session Continuity

Implement session continuity measures for disaster recovery scenarios:
  1. Session Replication: Replicate session data across multiple data centers
  2. Graceful Degradation: Implement fallback authentication mechanisms
  3. Session Recovery: Provide mechanisms to recover sessions after system failures
  4. Backup Authentication: Maintain backup authentication services

Differences from Integration

FeatureIntegrationProduction
Token ExpirationStandard (3600s)Shorter (1800s)
Required HeadersBasic setComprehensive set
Session MonitoringBasicEnterprise-grade
Concurrent SessionsUnlimitedLimited and monitored
Session Anomaly DetectionLimitedComprehensive

Integration Reference

For testing and validation before production deployment, refer to the Integration Session Management.

Playground Reference

For simplified testing and experimentation, you can always return to the Playground Session Management.

Need Production Support?

If you encounter any issues with session management in the Production environment, please contact our production support team at:
I