我正在编写一个将公开API的应用程序.该应用程序允许人们创建工作区并向其添加用户.每个用户都有一个唯一的令牌.当他们进行API调用时,他们将使用该令牌(将其标识为使用该工作空间的用户).
目前我这样做:
var w = new Workspace(); // This is a mongoose model
w.name = req.body.workspace;
w.activeFlag = true;
crypto.randomBytes(16, function(err, buf) {
if(err){
next(new g.errors.BadError503("Could not generate token") );
} else {
var token = buf.toString('hex');
// Access is the list of users who can access it. NOTE that
// the token is all they will pass when they use the API
w.access = { login: req.session.login, token:token, isOwner: true };
w.save( function(err){
if(err){
next(new g.errors.BadError503("Database error saving workspace") );
Run Code Online (Sandbox Code Playgroud)
这是生成API令牌的好方法吗?
由于令牌是名称+工作空间,也许我应该做一些像md5(用户名+工作空间+ secret_string)...?
sae*_*eed 19
如果你使用mongodb只使用ObjectId,我推荐使用substack的hat模块.
生成id很简单
var hat = require('hat');
var id = hat();
console.log(id); // 1c24171393dc5de04ffcb21f1182ab28
Run Code Online (Sandbox Code Playgroud)