Secure random token in Node.js

后端 未结 12 973
盖世英雄少女心
盖世英雄少女心 2020-11-28 00:05

In this question Erik needs to generate a secure random token in Node.js. There\'s the method crypto.randomBytes that generates a random Buffer. However, the ba

12条回答
  •  春和景丽
    2020-11-28 00:55

    The up-to-date right way to do this asynchronously using ES 2016 standards of async and await (as of Node 7) would be the following:

    const crypto = require('crypto');
    
    function generateToken({ stringBase = 'base64', byteLength = 48 } = {}) {
      return new Promise((resolve, reject) => {
        crypto.randomBytes(byteLength, (err, buffer) => {
          if (err) {
            reject(err);
          } else {
            resolve(buffer.toString(stringBase));
          }
        });
      });
    }
    
    async function handler(req, res) {
       // default token length
       const newToken = await generateToken();
       console.log('newToken', newToken);
    
       // pass in parameters - adjust byte length
       const shortToken = await generateToken({byteLength: 20});
       console.log('newToken', shortToken);
    }
    

    This works out of the box in Node 7 without any Babel transformations

提交回复
热议问题