You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Vidyo.io视频聊天实现Token生成服务器?

How to Build a Custom Vidyo Token Generation Server

Got it, let's break down how to build your own token generation server for Vidyo—since you've already used their test generator to validate your app, you're halfway there! Vidyo tokens are just signed JSON Web Tokens (JWTs) with specific platform claims, so the process is manageable once you know the key pieces.

First, Understand the Core Token Requirements

Every valid Vidyo token needs these non-negotiable claims:

  • iss (Issuer): Your unique Vidyo Developer API Key (find this in your Vidyo Developer Portal account)
  • sub (Subject): A unique identifier for the user requesting access (like their username or internal user ID)
  • exp (Expiration Time): A timestamp for when the token expires (always set this—permanent tokens are a huge security risk)
  • vidyoToken: A nested object with platform-specific details, most importantly the resourceUri pointing to the room/service the user is accessing

Step 1: Pick Your Backend Tech Stack

You can build this with almost any backend language. Here are two common, easy-to-implement options:

Option 1: Node.js + Express

Lightweight and fast to set up—you'll just need the jsonwebtoken library:

  1. Install dependencies:
    npm install express jsonwebtoken cors
    
  2. Basic server code:
    const express = require('express');
    const jwt = require('jsonwebtoken');
    const cors = require('cors');
    const app = express();
    
    app.use(cors());
    app.use(express.json());
    
    // Replace these with your actual Vidyo credentials (store in env vars in production!)
    const VIDYO_API_KEY = 'your-vidyo-api-key';
    const VIDYO_SECRET_KEY = 'your-vidyo-secret-key';
    
    app.post('/generate-token', (req, res) => {
      const { userId, roomName } = req.body;
      if (!userId || !roomName) {
        return res.status(400).json({ error: 'userId and roomName are required' });
      }
    
      const tokenPayload = {
        iss: VIDYO_API_KEY,
        sub: userId,
        exp: Math.floor(Date.now() / 1000) + 3600, // Expires in 1 hour
        vidyoToken: {
          resourceUri: `https://vidyo.io/service/v1/room/${roomName}`,
          permission: 'JOIN' // Adjust to 'MODERATE' if needed for room admins
        }
      };
    
      const signedToken = jwt.sign(tokenPayload, VIDYO_SECRET_KEY, { algorithm: 'HS256' });
      res.json({ token: signedToken });
    });
    
    app.listen(3000, () => {
      console.log('Vidyo token server running on port 3000');
    });
    

Option 2: Python + Flask

Great if you prefer Python—use the PyJWT library:

  1. Install dependencies:
    pip install flask pyjwt python-dotenv
    
  2. Basic server code:
    from flask import Flask, request, jsonify
    import jwt
    import os
    from datetime import datetime, timedelta
    from dotenv import load_dotenv
    
    load_dotenv()
    app = Flask(__name__)
    
    VIDYO_API_KEY = os.getenv('VIDYO_API_KEY')
    VIDYO_SECRET_KEY = os.getenv('VIDYO_SECRET_KEY')
    
    @app.route('/generate-token', methods=['POST'])
    def generate_token():
        request_data = request.get_json()
        user_id = request_data.get('userId')
        room_name = request_data.get('roomName')
    
        if not user_id or not room_name:
            return jsonify({'error': 'userId and roomName are required'}), 400
    
        expiration_time = datetime.utcnow() + timedelta(hours=1)
        payload = {
            'iss': VIDYO_API_KEY,
            'sub': user_id,
            'exp': expiration_time,
            'vidyoToken': {
                'resourceUri': f'https://vidyo.io/service/v1/room/{room_name}',
                'permission': 'JOIN'
            }
        }
    
        signed_token = jwt.encode(payload, VIDYO_SECRET_KEY, algorithm='HS256')
        return jsonify({'token': signed_token})
    
    if __name__ == '__main__':
        app.run(port=3000, debug=True)
    

Step 2: Secure Your Server

Don't skip these critical steps:

  • Never hardcode secrets: Store your Vidyo API key and secret in environment variables (use .env files locally, and your hosting provider's secret manager in production)
  • Protect your token endpoint: Add authentication (like API key checks or OAuth2) so only your app's users can request tokens—don't let random internet traffic hit this endpoint
  • Keep expiration times short: 1 hour is a safe default; adjust based on your use case (e.g., 15 minutes for one-off meetings)

Step 3: Test Your Server

Validate it works before integrating with your app:

  • Use curl or Postman to send a POST request:
    curl -X POST http://localhost:3000/generate-token \
      -H "Content-Type: application/json" \
      -d '{"userId": "user_123", "roomName": "team_meeting_001"}'
    
  • Take the returned token, plug it into your Vidyo app, and confirm it works exactly like the test token you used before. If it fails, use a JWT decoder to check if all claims are correctly formatted.

Step 4: Deploy Your Server

Once local testing passes, deploy to a hosting service like Heroku, AWS EC2, or DigitalOcean. Make sure:

  • Your server uses HTTPS (most providers offer free certificates via Let's Encrypt)
  • All environment variables are configured on your hosting platform
  • You set up basic monitoring to ensure the server stays online

Pro Tip: If you run into validation errors, double-check that your secret key matches exactly what's in your Vidyo Developer Portal—even a single typo will break token signing.

内容的提问来源于stack exchange,提问作者Wassauf Khalid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:54:35