API Authentication
This guide covers configuring API authentication for License Monitor to secure access to endpoints.
Authentication Methods
Section titled “Authentication Methods”License Monitor supports multiple authentication methods:
| Method | Use Case | Configuration |
|---|---|---|
| API Key (Header) | Server-to-server | X-API-Key header |
| API Key (Query) | WebSocket/SSE | ?api_key= parameter |
| Bearer Token | JWT integration | Authorization: Bearer |
API Key Authentication
Section titled “API Key Authentication”Generating API Keys
Section titled “Generating API Keys”Generate a secure API key:
openssl rand -hex 32# Output: a1b2c3d4e5f6...import secretsprint(secrets.token_hex(32))const crypto = require('crypto');console.log(crypto.randomBytes(32).toString('hex'));Configuration
Section titled “Configuration”Configure API key authentication in config.toml:
[api]enabled = truebind_address = "127.0.0.1"bind_port = 8080
# API Key Configurationapi_key = "your-secure-api-key-here"require_auth = trueOr via environment variable:
export LICENSE_MONITOR_API_KEY="your-secure-api-key-here"Using API Keys
Section titled “Using API Keys”Header Authentication (Recommended)
Section titled “Header Authentication (Recommended)”# Using X-API-Key headercurl -H "X-API-Key: your-api-key" \ http://localhost:8080/api/health
# Using Authorization headercurl -H "Authorization: ApiKey your-api-key" \ http://localhost:8080/api/healthQuery Parameter (WebSocket/SSE)
Section titled “Query Parameter (WebSocket/SSE)”# For WebSocket connectionswscat -c "ws://localhost:8080/ws/logs?api_key=your-api-key"
# For SSE connectionscurl "http://localhost:8080/stream/logs?api_key=your-api-key"Client Implementation
Section titled “Client Implementation”JavaScript/TypeScript
Section titled “JavaScript/TypeScript”const API_KEY = process.env.LICENSE_MONITOR_API_KEY;const BASE_URL = 'http://localhost:8080';
// REST API callsasync function fetchHealth() { const response = await fetch(`${BASE_URL}/api/health`, { headers: { 'X-API-Key': API_KEY, 'Content-Type': 'application/json', }, }); return response.json();}
// WebSocket connectionconst ws = new WebSocket(`${BASE_URL}/ws/logs?api_key=${API_KEY}`);ws.onmessage = (event) => { console.log('Received:', JSON.parse(event.data));};
// SSE connectionconst eventSource = new EventSource( `${BASE_URL}/stream/logs?api_key=${API_KEY}`);eventSource.onmessage = (event) => { console.log('Received:', JSON.parse(event.data));};Python
Section titled “Python”import requestsimport os
API_KEY = os.environ.get('LICENSE_MONITOR_API_KEY')BASE_URL = 'http://localhost:8080'
headers = { 'X-API-Key': API_KEY, 'Content-Type': 'application/json',}
# GET requestresponse = requests.get(f'{BASE_URL}/api/health', headers=headers)print(response.json())
# POST requestresponse = requests.post( f'{BASE_URL}/api/execute', headers=headers, json={'command': 'lmstat', 'args': ['-a']})print(response.json())cURL Examples
Section titled “cURL Examples”# Health checkcurl -X GET \ -H "X-API-Key: $LICENSE_MONITOR_API_KEY" \ http://localhost:8080/api/health
# Get licensescurl -X GET \ -H "X-API-Key: $LICENSE_MONITOR_API_KEY" \ http://localhost:8080/api/licenses
# Execute commandcurl -X POST \ -H "X-API-Key: $LICENSE_MONITOR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"command": "lmstat", "args": ["-a"]}' \ http://localhost:8080/api/executeMultiple API Keys
Section titled “Multiple API Keys”For environments requiring different access levels:
[api]# Primary API key for full accessapi_key = "primary-admin-key"
# Read-only API keyapi_key_readonly = "readonly-monitoring-key"
# Webhook API keyapi_key_webhook = "webhook-integration-key"Key Permissions
Section titled “Key Permissions”| Key Type | Endpoints | Methods |
|---|---|---|
| Primary | All | GET, POST |
| Read-only | /api/health, /api/licenses, /api/status | GET |
| Webhook | /api/webhook/* | POST |
Key Rotation
Section titled “Key Rotation”Rotation Procedure
Section titled “Rotation Procedure”-
Generate new key
Terminal window NEW_KEY=$(openssl rand -hex 32)echo "New key: $NEW_KEY" -
Update configuration
Terminal window # Update config file or environmentsed -i "s/api_key = .*/api_key = \"$NEW_KEY\"/" /etc/license-monitor/config.toml -
Restart service
Terminal window systemctl restart license-monitor -
Update clients
- Update all client applications with new key
- Verify connectivity
-
Revoke old key
- Remove old key from all configurations
- Monitor for failed authentication attempts
Graceful Rotation
Section titled “Graceful Rotation”For zero-downtime rotation, support multiple active keys temporarily:
[api]# Support both old and new keys during rotationapi_keys = [ "new-api-key-12345", "old-api-key-67890" # Remove after rotation complete]Authentication Failures
Section titled “Authentication Failures”Response Codes
Section titled “Response Codes”| Code | Description | Action |
|---|---|---|
| 401 | Missing or invalid API key | Provide valid key |
| 403 | Key valid but insufficient permissions | Use key with proper permissions |
| 429 | Rate limit exceeded | Reduce request rate |
Error Response Format
Section titled “Error Response Format”{ "error": "Unauthorized", "code": "AUTH_FAILED", "message": "Invalid or missing API key", "requestId": "req-12345"}Monitoring Auth Failures
Section titled “Monitoring Auth Failures”# View authentication failures in logsgrep "AUTH_FAILED" /var/log/license-monitor/license_monitor.log
# Count failures by IPgrep "AUTH_FAILED" /var/log/license-monitor/license_monitor.log | \ awk '{print $NF}' | sort | uniq -c | sort -rnSecurity Best Practices
Section titled “Security Best Practices”- Never commit API keys to version control
- Use environment variables or secrets manager
- Rotate keys regularly (every 90 days recommended)
- Use different keys for different environments
- Monitor authentication failures and alert on anomalies
- Use TLS for all API communications
- Implement IP whitelisting where possible
Service Account Setup
Section titled “Service Account Setup”For automated integrations, create dedicated service accounts:
# Create service-specific keySERVICE_KEY=$(openssl rand -hex 32)
# Document the key purposecat >> /etc/license-monitor/api-keys.md << EOF## Monitoring Service Key- Created: $(date)- Purpose: Prometheus metrics collection- Permissions: Read-only- Key prefix: ${SERVICE_KEY:0:8}...EOF
# Store securelyecho "MONITORING_API_KEY=$SERVICE_KEY" >> /etc/license-monitor/service-keys.envNext Steps
Section titled “Next Steps”- Network Security - IP whitelisting and firewalls
- Rate Limiting - Request throttling
- CORS Configuration - Cross-origin settings