Token Authentication
Secure authentication using CloudSignal's token system
Token Authentication
Tokens provide secure, time-limited authentication for MQTT connections. Tokens are automatically refreshed before expiration.
How It Works
- Your backend requests a token from CloudSignal's API
- The client receives the token and authenticates
- Tokens auto-refresh before expiration (default: 60 minutes TTL)
Configuration
Enable token authentication by providing your API credentials:
import { CloudSignalClient } from '@cloudsignal/mqtt-client';
const client = new CloudSignalClient({
organizationId: 'your-org-id',
apiKey: 'your-api-key',
auth: {
enabled: true,
userId: 'user-123',
tokenRefreshBuffer: 300 // Refresh 5 min before expiry
}
});
Server-Side Token Generation
For production, generate tokens on your backend:
// Your backend endpoint
const response = await fetch('https://api.cloudsignal.io/tokens', {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
organization_id: 'your-org-id',
user_id: 'user-123',
permissions: ['publish', 'subscribe'],
topics: ['chat/#', 'notifications/user-123']
})
});
const { token, expires_at } = await response.json();
Client-Side with Pre-Generated Token
Pass a pre-generated token to the client:
const client = new CloudSignalClient({
organizationId: 'your-org-id',
auth: {
enabled: true,
token: preGeneratedToken,
onTokenExpiring: async () => {
// Fetch a new token from your backend
const newToken = await fetchNewToken();
return newToken;
}
}
});
Token Permissions
Tokens support fine-grained permissions:
publish- Allow publishing to specified topicssubscribe- Allow subscribing to specified topicspresence- Access presence informationhistory- Access message history
Topic Patterns
Use MQTT wildcards in topic permissions:
chat/#- Match all topics underchat/user/+/messages- Match single-level wildcardsensors/temperature- Exact topic match
Auto-Refresh Behavior
The client automatically refreshes tokens:
const client = new CloudSignalClient({
organizationId: 'your-org-id',
auth: {
enabled: true,
tokenRefreshBuffer: 300, // 5 minutes
maxRefreshRetries: 3
}
});
// Listen for token events
client.on('token:refreshed', () => {
console.log('Token refreshed successfully');
});
client.on('token:error', (error) => {
console.error('Token refresh failed:', error);
});
Security Best Practices
- Never expose API keys in client code - Generate tokens server-side
- Use short TTLs - Default 60 minutes is recommended
- Scope permissions narrowly - Only grant necessary topic access
- Rotate API keys periodically - Update keys every 90 days