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

  1. Your backend requests a token from CloudSignal's API
  2. The client receives the token and authenticates
  3. 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 topics
  • subscribe - Allow subscribing to specified topics
  • presence - Access presence information
  • history - Access message history

Topic Patterns

Use MQTT wildcards in topic permissions:

  • chat/# - Match all topics under chat/
  • user/+/messages - Match single-level wildcard
  • sensors/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

  1. Never expose API keys in client code - Generate tokens server-side
  2. Use short TTLs - Default 60 minutes is recommended
  3. Scope permissions narrowly - Only grant necessary topic access
  4. Rotate API keys periodically - Update keys every 90 days