Authentication
Token Authentication
Secure authentication using CloudSignal's token system
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 with connectWithToken. Pass your secret key and organization ID, and the client handles token acquisition and refresh:
import CloudSignal from '@cloudsignal/mqtt-client';
const client = new CloudSignal({
autoRefresh: true // Refresh tokens automatically before expiry
});
await client.connectWithToken({
host: 'your-broker-host',
organizationId: 'your-org-id',
secretKey: 'your-secret-key',
userEmail: 'user-123'
});Server-Side Token Generation
For production, generate tokens on your backend:
// Your backend endpoint
const response = await fetch('https://auth.cloudsignal.app/v2/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 as an externalToken:
import CloudSignal from '@cloudsignal/mqtt-client';
const client = new CloudSignal();
// Notified shortly before the current token expires
client.setTokenExpiringCallback(() => {
console.log('Token is expiring soon');
});
await client.connectWithToken({
host: 'your-broker-host',
organizationId: 'your-org-id',
externalToken: preGeneratedToken
});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 when autoRefresh is enabled:
import CloudSignal from '@cloudsignal/mqtt-client';
const client = new CloudSignal({
autoRefresh: true
});
// Listen for token events
client.setTokenRefreshedCallback(() => {
console.log('Token refreshed successfully');
});
client.setTokenErrorCallback((error) => {
console.error('Token refresh failed:', error);
});
await client.connectWithToken({
host: 'your-broker-host',
organizationId: 'your-org-id',
secretKey: 'your-secret-key'
});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