CloudSignal Docs
GuidesAuth Providers

Firebase integration

Configure Firebase Authentication as a provider for CloudSignal MQTT.

Configure Firebase Authentication as an auth provider so your Firebase users can connect to CloudSignal MQTT with credentials derived from their Firebase ID token. Use this when your app already authenticates users via Firebase Auth.

Prerequisites

  • A Firebase project with authentication enabled
  • A CloudSignal account with API keys
  • Firebase Admin SDK credentials (service account)

Configuration

Get Firebase project ID

  1. Go to Firebase Console
  2. Select your project
  3. Go to Project Settings (gear icon)
  4. Copy the Project ID

Add Firebase provider in CloudSignal

  1. Go to CloudSignal Dashboard
  2. Navigate to ConnectionsAuth Providers
  3. Click Add Provider
  4. Select Firebase
  5. Enter your configuration:
FieldValue
NameA friendly name (for example, "Production Firebase")
Project IDYour Firebase project ID
  1. Click Save

Test the integration

Exchange a Firebase ID token:

curl -X POST https://api.cloudsignal.io/v2/tokens/exchange \
  -H "Authorization: Bearer YOUR_CLOUDSIGNAL_SK" \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "firebase",
    "token": "YOUR_FIREBASE_ID_TOKEN"
  }'

Implementation

React/Next.js example

import { initializeApp } from 'firebase/app';
import { getAuth, onAuthStateChanged } from 'firebase/auth';
import mqtt from 'mqtt';

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

// Exchange Firebase token for MQTT credentials
async function getMqttCredentials() {
  const user = auth.currentUser;

  if (!user) {
    throw new Error('User not authenticated');
  }

  // Get Firebase ID token
  const idToken = await user.getIdToken();

  // Exchange via your backend
  const response = await fetch('/api/mqtt-credentials', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ firebaseToken: idToken })
  });

  return response.json();
}

// Connect to MQTT
async function connectMqtt() {
  const credentials = await getMqttCredentials();

  const client = mqtt.connect('wss://connect.cloudsignal.app:18885/', {
    username: credentials.mqtt_username,
    password: credentials.mqtt_password
  });

  client.on('connect', () => {
    console.log('Connected to MQTT');
  });

  return client;
}

API route (Next.js)

// app/api/mqtt-credentials/route.ts
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  const { firebaseToken } = await request.json();

  const response = await fetch('https://api.cloudsignal.io/v2/tokens/exchange', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.CLOUDSIGNAL_SK}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      provider: 'firebase',
      token: firebaseToken
    })
  });

  const credentials = await response.json();
  return NextResponse.json(credentials);
}

React Native / Expo example

import auth from '@react-native-firebase/auth';
import mqtt from 'mqtt';

async function connectToMqtt() {
  const currentUser = auth().currentUser;

  if (!currentUser) {
    throw new Error('Not logged in');
  }

  // Get Firebase ID token
  const idToken = await currentUser.getIdToken();

  // Exchange token via your backend
  const response = await fetch('https://your-api.com/mqtt-credentials', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${idToken}`,
      'Content-Type': 'application/json'
    }
  });

  const { mqtt_username, mqtt_password } = await response.json();

  // Connect to MQTT
  const client = mqtt.connect('wss://connect.cloudsignal.app:18885/', {
    username: mqtt_username,
    password: mqtt_password
  });

  return client;
}

Flutter example

import 'package:firebase_auth/firebase_auth.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_browser_client.dart';

class MqttService {
  MqttBrowserClient? client;

  Future<void> connect() async {
    // Get Firebase ID token
    final user = FirebaseAuth.instance.currentUser;
    if (user == null) throw Exception('Not authenticated');

    final idToken = await user.getIdToken();

    // Exchange for MQTT credentials
    final response = await http.post(
      Uri.parse('https://your-api.com/mqtt-credentials'),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({'firebaseToken': idToken}),
    );

    final credentials = jsonDecode(response.body);

    // Connect to MQTT
    client = MqttBrowserClient(
      'wss://connect.cloudsignal.app:18885/',
      'flutter_client'
    );

    client!.setProtocolV311();

    await client!.connect(
      credentials['mqtt_username'],
      credentials['mqtt_password']
    );
  }
}

Handling token refresh

Firebase ID tokens expire after 1 hour. Handle this gracefully:

import { getAuth, onIdTokenChanged } from 'firebase/auth';

const auth = getAuth();
let mqttClient: mqtt.MqttClient | null = null;

// Listen for token changes
onIdTokenChanged(auth, async (user) => {
  if (user && mqttClient) {
    // Get fresh MQTT credentials
    const credentials = await getMqttCredentials();

    // Reconnect with new credentials
    mqttClient.end();
    mqttClient = mqtt.connect('wss://connect.cloudsignal.app:18885/', {
      username: credentials.mqtt_username,
      password: credentials.mqtt_password
    });
  }
});

ACL rules for Firebase users

Create ACL rules that match Firebase user UIDs:

# User can only access their own topics
User Pattern: %
Topic: users/%u/#
Permission: pubsub

The MQTT username will be derived from the Firebase UID or email.

Troubleshooting

"Invalid token" error

CheckWhat to verify
Token freshnessFirebase ID tokens expire after 1 hour
Project IDMust match your Firebase project exactly
Token typeUse user.getIdToken(), not custom tokens

"Provider not found" error

CheckWhat to verify
Provider enabledConfirm the provider is enabled in CloudSignal
Provider nameUse "provider": "firebase" (lowercase)

"Token verification failed"

CheckWhat to verify
Firebase project statusEnsure Auth is enabled
Token formatShould be a valid JWT

Next steps

On this page