Gary
Gary

Reputation: 1017

In Node.js, is it possible to run a middleware function asynchronously?

I've built a middleware function to validate user access tokens (JWT) ... if the JWT has expired, I automatically create a new access token from the user's refresh token (if it as well is valid, of course).

I imagine that at some point, if I have enough users, authorization could be a bottleneck. I'd like to ensure these functions are running asynchronously (e.g. via the UV threadpool).

Is this possible, or do I even have to worry about this?

ADDENDUM:

This is the decryption routine I'm using in my middleware function. I'm also using jsonwebtoken.

'use strict';

const cryptoAsync = require('@ronomon/crypto-async');
const crypto = require('crypto');
const util = require('util');

class AES {
    constructor(key, iv, bitSize) {
      // supported stream ciphers:
      // aes-256-ctr (keySize=32, ivSize=16)
      // aes-192-ctr (keySize=24, ivSize=16)
      // aes-128-ctr (keySize=16, ivSize=16)

      if (!bitSize) bitSize = 128;

      if (bitSize !== 256 && bitSize !== 192 && bitSize !== 128) {
        throw new Error('AES requires a bitsize of 256, 192, or 128.');
      }

      if (!key || key.length !== bitSize/8) throw new Error(`A ${bitSize/8}-byte/${bitSize}-bit key is required.`);

      if (!iv || iv.length !== 16) throw new Error('A 16-byte/128-bit initialization vector is required.');

      this.algo = `aes-${bitSize}-ctr`;
      this.key = key;
      this.iv = iv;

      console.log(`Using the ${this.algo} algorithm ...`);
    }
 
    async encrypt(dataAsUtf8) {
        const cipherText = await util.promisify(cryptoAsync.cipher)(this.algo, 1, this.key, this.iv, Buffer.from(dataAsUtf8, 'utf8'));

        return cipherText.toString('hex');
    }

    async decrypt(dataAsHex) {
    if (!Buffer.isEncoding('hex')) throw new Error('Input must be in HEX format.');

        const cipherText = await util.promisify(cryptoAsync.cipher)(this.algo, 0, this.key, this.iv, Buffer.from(dataAsHex, 'hex'));

        return cipherText.toString('utf8');
    }

    static randomBytes = async bytes => {
        const bytesAsBuffer = await util.promisify(crypto.randomBytes)(bytes);

    return bytesAsBuffer;
    }
}

module.exports = AES;

Upvotes: 0

Views: 138

Answers (1)

see sharper
see sharper

Reputation: 12035

It's actually pretty hard to write code that blocks the main thread in Node for a significant time unless you are doing some seriously heavy lifting, such as generating very large reports or the like. Authorization via JWT tokens is totally lightweight and will not be a problem, I can virtually guarantee that. You will not need to push that type of work off onto a separate thread, if that was the plan.

Upvotes: 1

Related Questions