使用Node JS生成Twillio访问令牌

时间:2017-07-26 04:19:13

标签: javascript node.js twilio twilio-api

我正在开发一个使用Twillios Programmable Video 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提供的这个具体示例中,我假设必须的视频授权是明确引用的,但是对于这个特定的令牌生成器,用户只能输入该名称的房间。

我想知道在配置令牌之前是否可以引用房间。类似于身份是在输出令牌之前输入到函数中的变量的方式。

另外,在Twillios自己的函数环境之外创建标记时是否有任何必需的依赖项或库?

非常感谢任何答案,建议或参考。

1 个答案:

答案 0 :(得分:4)

Twilio开发者传道者在这里。

也可以将房间名称作为变量提供。您可能希望创建一个可以将标识和房间名称作为参数并返回访问令牌的函数。像这样:

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");

让我知道这是否有帮助。