Secure API Authentication with JWT Tokens
Overview
This comprehensive guide walks you through implementing JWT (JSON Web Token) based authentication for secure API communication with the sulus.ai platform. Learn how to create, configure, and utilize JWT tokens for both private and public API access scenarios.
Getting Started
Required Setup
To begin implementing JWT authentication, you’ll need:
- Development environment with JWT token generation capabilities
- Valid sulus.ai account credentials
- Proper environment variable configuration
- Your organization identifier and signing key (available in your sulus.ai dashboard)
Security Considerations
JWT tokens provide stateless authentication by encoding user claims and organizational data directly into cryptographically signed tokens. This approach ensures secure API communication without requiring server-side session management.
Token Creation Process
Step-by-Step Implementation
1. Configure Your Payload Data Structure your token payload with essential organizational information and access scope definitions.
2. Secure Key Management Retrieve your private signing key from secure storage (environment variables recommended for production).
3. Token Expiration Settings Define appropriate token lifecycle parameters to balance security with user experience.
4. Token Generation Execute the signing process using your chosen JWT implementation library.
Authorization Scope Management
Private Scope Tokens
Private scope tokens provide comprehensive API access for backend integrations and administrative operations. These tokens enable full platform functionality access.
Public Scope Tokens
Public scope tokens offer restricted access designed for client-side applications with specific security constraints and limited functionality requirements.
Important Note: Currently, web-based call creation (https://api.sulus.ai/call/web) represents the only publicly accessible endpoint. All additional functionality requires private scope authorization.
Implementation Examples
Creating Private Access Tokens
// Configure token payload for private scope access
const tokenPayload = {
orgId: process.env.SULUS_ORG_ID,
authorization: {
scope: "private",
},
};
// Load signing key from secure environment
const signingKey = process.env.SULUS_PRIVATE_KEY;
// Set token lifecycle parameters
const tokenConfiguration = {
expiresIn: "60m", // 1 hour expiration
};
// Generate signed token
const accessToken = createJWTToken(tokenPayload, signingKey, tokenConfiguration);
Creating Public Access Tokens
// Configure token payload for public scope with restrictions
const tokenPayload = {
orgId: process.env.SULUS_ORG_ID,
authorization: {
scope: "public",
limitations: {
active: true,
permittedDomains: ["https://yourdomain.sulus.ai"],
authorizedAssistants: ["a1b2c3d4-e5f6-7890-abcd-ef1234567890"],
enableTransientMode: false,
},
},
};
// Load signing key from secure environment
const signingKey = process.env.SULUS_PRIVATE_KEY;
// Set token lifecycle parameters
const tokenConfiguration = {
expiresIn: "60m",
};
// Generate signed token
const publicToken = createJWTToken(tokenPayload, signingKey, tokenConfiguration);
Token Payload Structure Explained
- Organization ID: Links the token to your specific sulus.ai account
- Authorization Scope: Determines available API endpoints and functionality
- Expiration Time: Controls token validity period for security
- Restrictions: (Public tokens only) Define usage limitations and security boundaries
API Integration Implementation
Private Token Usage
Private scope tokens enable comprehensive API access for server-side operations:
async function retrieveAssistantList() {
try {
const apiResponse = await fetch("https://api.sulus.ai/assistant", {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken}`,
},
});
const assistantData = await apiResponse.json();
return assistantData;
} catch (error) {
console.error("API request failed:", error);
throw error;
}
}
// Execute the API call
retrieveAssistantList()
.then(data => console.log("Retrieved assistants:", data))
.catch(error => console.error("Error:", error));
Client-Side Implementation
For public scope tokens in web applications:
import SulusClient from '@sulus-ai/web-client';
// Initialize client with public token
const sulusClient = new SulusClient('your-public-jwt-token');
// Start AI assistant session
sulusClient.initiateSession('your-assistant-identifier');
Best Practices
Security Recommendations
- Environment Variables: Store sensitive keys in environment variables, never in source code
- Token Rotation: Implement regular token refresh cycles for enhanced security
- Scope Limitation: Use public tokens for client-side operations, private tokens for server operations
- Domain Restrictions: Configure allowed origins for public tokens to prevent unauthorized usage
- Expiration Management: Set appropriate token lifespans based on your security requirements
Error Handling
Implement comprehensive error handling for authentication failures:
async function authenticatedRequest(endpoint, options = {}) {
try {
const response = await fetch(`https://api.sulus.ai${endpoint}`, {
...options,
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken}`,
...options.headers,
},
});
if (!response.ok) {
throw new Error(`Authentication failed: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("API authentication error:", error);
// Implement token refresh logic here
throw error;
}
}
Troubleshooting
Common Issues
- Token Expiration: Verify token hasn’t exceeded configured expiration time
- Invalid Signature: Ensure correct private key is being used for signing
- Scope Mismatch: Confirm token scope matches required endpoint access level
- Domain Restrictions: Check that request origin matches configured allowed domains
Testing Your Implementation
Validate your JWT implementation with this verification function:
function validateTokenStructure(token) {
try {
const decoded = JSON.parse(atob(token.split('.')[1]));
console.log("Token payload:", decoded);
// Verify required fields
if (!decoded.orgId || !decoded.authorization) {
throw new Error("Missing required token fields");
}
return true;
} catch (error) {
console.error("Token validation failed:", error);
return false;
}
}
Quick Start Guide
For experienced developers who want to get started immediately:
// 1. Install the sulus.ai SDK
npm install @sulus-ai/node-sdk
// 2. Generate token and make your first API call
import { SulusAuth, SulusClient } from '@sulus-ai/node-sdk';
const auth = new SulusAuth({
orgId: process.env.SULUS_ORG_ID,
privateKey: process.env.SULUS_PRIVATE_KEY
});
const client = new SulusClient(auth.generateToken());
const assistants = await client.assistants.list();
Advanced Configuration
Rate Limiting & Performance
The sulus.ai API implements intelligent rate limiting to ensure optimal performance:
- Private tokens: 1000 requests/minute
- Public tokens: 100 requests/minute
- Burst capacity: 2x rate limit for short periods
Implement token caching to optimize performance:
class TokenManager {
constructor(orgId, privateKey) {
this.orgId = orgId;
this.privateKey = privateKey;
this.cachedToken = null;
this.tokenExpiry = null;
}
getValidToken() {
const now = Date.now();
if (!this.cachedToken || now >= this.tokenExpiry) {
this.refreshToken();
}
return this.cachedToken;
}
refreshToken() {
const payload = {
orgId: this.orgId,
authorization: { scope: "private" },
iat: Math.floor(Date.now() / 1000)
};
this.cachedToken = createJWTToken(payload, this.privateKey, { expiresIn: "50m" });
this.tokenExpiry = Date.now() + (50 * 60 * 1000); // 50 minutes
}
}
Webhook Authentication
Verify incoming webhooks from sulus.ai using signature validation:
function verifyWebhookSignature(payload, signature, secret) {
const crypto = require('crypto');
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(`sha256=${expectedSignature}`),
Buffer.from(signature)
);
}
// Express.js webhook handler example
app.post('/sulus-webhook', (req, res) => {
const signature = req.headers['x-sulus-signature'];
if (!verifyWebhookSignature(req.body, signature, process.env.WEBHOOK_SECRET)) {
return res.status(401).send('Invalid signature');
}
// Process webhook payload
handleSulusWebhook(req.body);
res.status(200).send('OK');
});
Environment-Specific Configuration
Development Environment:
const devConfig = {
apiBase: "https://api.dev.sulus.ai",
tokenExpiration: "2h", // Longer for development convenience
logLevel: "debug"
};
Production Environment:
const prodConfig = {
apiBase: "https://api.sulus.ai",
tokenExpiration: "1h", // Shorter for security
logLevel: "error",
enableRetries: true,
retryBackoff: "exponential"
};
Integration with AI Phone Services
Connect your authentication with sulus.ai’s core AI phone capabilities:
// Initialize AI phone assistant with authenticated client
async function deployPhoneAssistant(assistantConfig) {
const token = tokenManager.getValidToken();
const response = await fetch("https://api.sulus.ai/phone/deploy", {
method: "POST",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
assistantId: assistantConfig.id,
phoneNumber: assistantConfig.phoneNumber,
businessHours: assistantConfig.schedule,
customWorkflows: assistantConfig.automations
})
});
return await response.json();
}
Monitoring & Analytics
Track API usage and performance with built-in analytics:
// Monitor token usage and API performance
class APIMonitor {
constructor(token) {
this.token = token;
this.metrics = {
requests: 0,
errors: 0,
avgResponseTime: 0
};
}
async makeRequest(endpoint, options = {}) {
const startTime = Date.now();
this.metrics.requests++;
try {
const response = await fetch(`https://api.sulus.ai${endpoint}`, {
...options,
headers: {
"Authorization": `Bearer ${this.token}`,
"X-Client-Version": "sulus-sdk-1.0.0",
...options.headers
}
});
// Track response time
const responseTime = Date.now() - startTime;
this.updateResponseTime(responseTime);
if (!response.ok) {
this.metrics.errors++;
throw new Error(`API Error: ${response.status}`);
}
return await response.json();
} catch (error) {
this.metrics.errors++;
throw error;
}
}
updateResponseTime(time) {
this.metrics.avgResponseTime =
(this.metrics.avgResponseTime + time) / 2;
}
getHealthMetrics() {
return {
...this.metrics,
errorRate: (this.metrics.errors / this.metrics.requests) * 100,
uptime: process.uptime()
};
}
}
Migration from Other Platforms
Streamlined migration helpers for developers moving from other AI phone services:
// Migration utility for common patterns
class PlatformMigrator {
// Convert from competitor API patterns to sulus.ai
static convertAssistantConfig(legacyConfig) {
return {
name: legacyConfig.bot_name || legacyConfig.assistant_name,
voice: this.mapVoiceSettings(legacyConfig.voice_config),
workflows: this.convertWorkflows(legacyConfig.automations),
schedule: this.normalizeSchedule(legacyConfig.business_hours)
};
}
static mapVoiceSettings(voiceConfig) {
// Convert voice settings from other platforms
return {
provider: "sulus-premium",
voice: voiceConfig.voice_id || "professional-female",
speed: voiceConfig.rate || 1.0,
pitch: voiceConfig.pitch || 0
};
}
}
Support & Resources
Official SDKs
- Node.js:
@sulus-ai/node-sdk - Python:
sulus-ai-python - PHP:
sulus-ai/php-sdk - Go:
github.com/sulus-ai/go-sdk
Community Resources
- GitHub Examples: github.com/sulus-ai/examples
- Developer Discord: Join our community for real-time support
- API Status: status.sulus.ai for uptime monitoring
This comprehensive authentication system provides enterprise-grade security and developer-friendly integration for your sulus.ai AI phone assistant platform, ensuring scalable and reliable communication between your applications and our advanced AI services.

