Skip to main content

Token Enrichment API

Overview

The Token Enrichment API provides a server-side endpoint that dynamically generates a JavaScript file for ### Performance Considerations

Response Time

  • Optimal Processing: Minimal no-op script for unauthenticated users (~100 bytes)
  • Efficient Generation: Full script only generated when authentication is available (~2KB)
  • Cached Configuration: Configuration values are cached by ASP.NET Core
  • No Database Calls: Uses in-memory authentication context

Bandwidth

  • Smart Payload Size:
    • Authenticated users: ~2KB (full functionality)
    • Unauthenticated users: ~100 bytes (no-op script)
  • Compression: Supports gzip compression when enabled
  • CDN Friendly: Can be cached at CDN level with appropriate headers adding authentication headers to HTTP requests. This feature enables seamless authentication for client-side applications consuming Lightstone APIs.

Endpoint

URL: /auth/token-enrichment.js
Method: GET
Content-Type: application/javascript
Authentication: Optional (graceful degradation for unauthenticated users)

Features

  • Automatic Header Injection: Intercepts XMLHttpRequest and fetch calls to add authentication headers
  • Lightstone API Targeting: Only adds headers for requests to apis.lightstone.co.za domains
  • Graceful Degradation: Works for both authenticated and unauthenticated users
  • Server-Side Token Management: Uses server-side authentication context instead of client-side storage
  • Cache Prevention: Implements appropriate cache headers to ensure fresh tokens

Configuration

Required Configuration

Add the following configuration to your appsettings.json files:

{
"Apis": {
"Authenticated": {
"ApiKey": "your-ocp-apim-subscription-key"
}
}
}

Environment-Specific Configuration

  • Development: Configure in appsettings.Development.json
  • Staging: Configure in appsettings.Staging.json
  • Production: Configure in appsettings.Production.json

Usage

Basic Integration

Include the script in your HTML pages:

<script src="/auth/token-enrichment.js"></script>

Advanced Integration

For applications that need to verify script loading:

// Load the token enrichment script
const script = document.createElement('script');
script.src = '/auth/token-enrichment.js';
script.onload = function() {
console.log('Token enrichment loaded successfully');
// Your application initialization code here
};
script.onerror = function() {
console.warn('Failed to load token enrichment');
// Handle the error case
};
document.head.appendChild(script);

Behavior

Authenticated Users

When a user is authenticated, the script:

  1. Intercepts HTTP Requests: Monitors XMLHttpRequest and fetch calls
  2. Filters Target URLs: Only processes requests to apis.lightstone.co.za domains
  3. Adds Authentication Headers:
    • Authorization: Bearer {access-token}
    • Ocp-Apim-Subscription-Key: {api-key}
  4. Preserves Existing Headers: Won't override manually set Authorization headers

Unauthenticated Users

When a user is not authenticated, the endpoint:

  1. Returns Minimal Script: Serves a lightweight no-op function (~100 bytes vs ~2KB)
  2. No Header Injection: No XMLHttpRequest or fetch interception occurs
  3. Optimal Performance: Minimal parsing and execution overhead for browsers

Error Handling

The endpoint handles various error scenarios efficiently:

  • Missing Access Token: Returns minimal no-op script
  • Missing API Key: Logs warning and returns minimal no-op script
  • Authentication Service Errors: Returns minimal no-op script gracefully
  • Configuration Errors: Falls back to minimal no-op script

All error scenarios result in a lightweight response (~100 bytes) rather than a full empty script structure.

Security Considerations

Access Token Security

  • Server-Side Generation: Tokens are embedded server-side, reducing client-side exposure
  • No Caching: Appropriate cache headers prevent token caching in browsers
  • Short-Lived Tokens: Uses standard OAuth token lifetimes

API Key Security

  • Configuration-Based: API keys are stored in secure configuration
  • Environment-Specific: Different keys for different environments
  • No Client-Side Storage: Keys are embedded at request time, not stored

Request Filtering

  • Domain Restriction: Only adds headers for Lightstone API domains
  • Google Exclusion: Explicitly excludes Google domains to prevent header leakage
  • HTTPS Enforcement: Only processes HTTPS requests in production

Testing

Unit Tests

The implementation includes comprehensive unit tests covering:

  • Authentication Scenarios: Authenticated and unauthenticated users
  • Error Handling: Missing tokens, API keys, and service failures
  • JavaScript Generation: Correct script structure and content
  • HTTP Headers: Proper cache control and content-type headers

Integration Testing

To test the endpoint manually:

# Test with unauthenticated user
curl -i http://localhost:5000/auth/token-enrichment.js

# Test with authenticated user (requires valid session)
curl -i -b "cookies.txt" http://localhost:5000/auth/token-enrichment.js

Performance Considerations

Response Time

  • Minimal Processing: Script generation is lightweight
  • Cached Configuration: Configuration values are cached by ASP.NET Core
  • No Database Calls: Uses in-memory authentication context

Bandwidth

  • Small Payload: Generated JavaScript is typically < 2KB
  • Compression: Supports gzip compression when enabled
  • CDN Friendly: Can be cached at CDN level with appropriate headers

Troubleshooting

Common Issues

Script Not Loading Authentication Headers

  • Verify user is authenticated in the application
  • Check that Apis:Authenticated:ApiKey is configured
  • Confirm requests are targeting apis.lightstone.co.za domains

Configuration Not Found

  • Ensure Apis:Authenticated:ApiKey exists in configuration
  • Verify configuration is available in the environment
  • Check application startup logs for configuration errors

Headers Not Being Added

  • Confirm script is loaded before making API calls
  • Verify target URLs contain apis.lightstone.co.za
  • Check browser developer tools for JavaScript errors

Logging

The endpoint logs the following events:

  • Debug: Script requests and generation
  • Warning: Missing API key configuration
  • Error: Authentication service failures and exceptions

Enable debug logging in appsettings.json:

{
"Logging": {
"LogLevel": {
"Apex.Portal.ServerApp.Controllers.AuthenticationController": "Debug"
}
}
}

API Reference

Response Headers

Content-Type: application/javascript
Cache-Control: no-cache, no-store, max-age=0
Pragma: no-cache
Expires: 0

JavaScript API

The generated script provides the following functionality:

// Automatically intercepts and modifies:
XMLHttpRequest.prototype.open()
window.fetch()

// Internal function (not exposed):
function getHeaderValues(url) {
// Returns authentication headers for Lightstone API URLs
// Returns empty array for other URLs or unauthenticated users
}

Version History

  • v1.0.0: Initial implementation with basic token enrichment
  • Support for authenticated and unauthenticated users
  • Configurable API key management
  • Comprehensive error handling and testing