Overview
All WebSocket connections must be authenticated using a JSON Web Token (JWT) for security.
Token Request
Authentication Endpoint
POST /api/websocket-voice/token
{
"apiKey": "YOUR_DEVICE_API_KEY",
"deviceId": "YOUR_DEVICE_UUID"
}
Content-Type: application/json
Responses
Status: 200 OK{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
The JWT token is short-lived (1 minute) and must be used immediately.
Implementation
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
Future<String> fetchAuthToken() async {
final response = await http.post(
Uri.parse('${dotenv.env['API_BASE_URL']}/api/websocket-voice/token'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'apiKey': dotenv.env['DEVICE_API_KEY'],
'deviceId': dotenv.env['DEVICE_ID'],
}),
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
return data['token'];
} else {
final errorData = jsonDecode(response.body);
throw Exception('Authentication failed: ${errorData['message']}');
}
}
Important Notes
Token Expiration: Tokens expire after 1 minute. Request a new token for each WebSocket connection.
No Caching
Never store or cache tokens - they’re single-use
Error Handling
Always handle authentication errors gracefully
Fresh Tokens
Request new token for each connection attempt
Immediate Use
Use tokens immediately after receiving them
Next Steps
With authentication working:
- Connect via WebSocket →
- See complete implementation →