I am writing an app that will expose an API. The application allows people to create workspaces and add users to them. Each user will have a unique token. When they make an API call, they will use that token (which will identify them as that user using that workspace.
At the moment I am doing this:
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") );
My question is: is this enough? I don't think I will have billions of users (there is always hope :D ); however, is this a good way to generate API tokens?
Or, since the token is name+workspace, maybe I should do something like md5(username+workspace+secret_string) ...?
Thanks!
If you using mongodb just use ObjectId, othewise I recommend substack's hat module.
To generate id is simple as
var hat = require('hat');
var id = hat();
console.log(id); // 1c24171393dc5de04ffcb21f1182ab28
How does this code make sure your token is unique? I believe you could have collision of numbers with this code. I believe you need to have a sort of sequence number like in this commit from socket.io.
Also you could use npm projects like for example:
to ensure uniqueness.
Why not just use UUIDv4 if you are looking for something unique? If you are interested in some other type of hashing (as mentioned previous hat is a good choice), you might look at speakeasy - https://github.com/markbao/speakeasy. It not only generates random keys but it can also create timebased twofactor authentication keys if you ever really want to layer on additional security strength.