Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating API tokens using node

Tags:

node.js

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

Is this a good way to generate API tokens?

Since the token is name+workspace, maybe I should do something like md5(username+workspace+secret_string) ...?

like image 401
Merc Avatar asked Aug 27 '12 03:08

Merc


People also ask

Can we use a node to develop an API?

Follow the steps given below to build a secure Node js REST API: Step 1: Create the Required Directories. Step 2: Create your First App Express API. Step 3: Creating the User Module.

What are node tokens?

JSON Web Tokens (JWT) are an RFC 7519 open industry standard for representing claims between two parties. For example, you can use jwt.io to decode, verify, and produce JWT. JWT specifies a compact and self-contained method for communicating information as a JSON object between two parties.


1 Answers

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
like image 165
saeed Avatar answered Oct 11 '22 10:10

saeed