javascript - 使用 Node JS 生成 Twillio 访问 token

标签 javascript node.js twilio twilio-api

我正在开发一个使用 Twillios 可编程视频 API 的应用程序。

我是 Node JS 的新手,但文档相当简单,但我仍然有几个问题。

这是我引用的代码。

const AccessToken = require('twilio').jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;

// Used when generating any kind of tokens
const twilioAccountSid = 'ACxxxxxxxxxx';
const twilioApiKey = 'SKxxxxxxxxxx';
const twilioApiSecret = 'xxxxxxxxxxxx';

const identity = 'user';

// Create Video Grant
const videoGrant = new VideoGrant({
room: 'cool room'
});

// Create an access token which we will sign and return to the client,
// containing the grant we just created
const token = new AccessToken(twilioAccountSid, twilioApiKey, twilioApiSecret);
token.addGrant(videoGrant);
token.identity = identity;

// Serialize the token to a JWT string
console.log(token.toJwt());

在 Twillio 提供的这个特定示例中,明确引用了我认为是强制性的视频授权,但这意味着对于这个特定的 token 生成器,用户只能进入该名称的房间。

我想知道是否可以在配置 token 之前引用房间。类似于标识是在输出 token 之前输入到函数中的变量。

另外,在Twillios自身的函数环境之外创建代币时,是否需要任何依赖或库?

非常感谢任何答案、建议或引用。

最佳答案

此处为 Twilio 开发人员布道师。

也可以将房间名称作为变量提供。您可能想要创建一个可以将身份和房间名称作为参数并返回访问 token 的函数。像这样:

const AccessToken = require('twilio').jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;

// Used when generating any kind of tokens
const twilioAccountSid = 'ACxxxxxxxxxx';
const twilioApiKey = 'SKxxxxxxxxxx';
const twilioApiSecret = 'xxxxxxxxxxxx';


function generateToken(identity, roomName) {
  const videoGrant = new VideoGrant({
    room: roomName
  });
  const token = new AccessToken(twilioAccountSid, twilioApiKey, twilioApiSecret);
  token.addGrant(videoGrant);
  token.identity = identity;
  return token.toJwt();
}

然后你可以使用如下函数:

const token = generateToken("Stefan", "StefansRoom");

让我知道这是否有帮助。

关于javascript - 使用 Node JS 生成 Twillio 访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45317394/

相关文章:

node.js - 无法在字符串上创建属性 'mark'

node.js - 在套接字发出的数据中引入延迟

node.js - 如何将mongoose js模型转换为对象

twilio - 黑客通过我的 FreePBX IVR 调用国际电话

javascript - 检查对象内哪个数组的长度最大

javascript - 用简单的英语解释使用高阶函数的好处

javascript - 显示 DOM 元素事件及其处理程序

javascript - JQuery - 多个复选框操作

android - Twilio Voip session 是否加密?

python - 为什么 Twilio Rest API 中的 "from"后面有一个下划线?