【发布时间】:2020-08-10 00:07:28
【问题描述】:
我已经构建了一个中间件函数来验证用户访问令牌 (JWT) ...如果 JWT 已过期,我会自动从用户的刷新令牌创建一个新的访问令牌(当然,如果它也是有效的) .
我想在某个时候,如果我有足够的用户,授权可能会成为瓶颈。我想确保这些函数异步运行(例如通过 UV 线程池)。
这可能吗,或者我什至需要担心这个?
附录:
这是我在中间件函数中使用的解密例程。我也在使用 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;
【问题讨论】:
-
在 Node.js 中,“异步”通常是指不阻塞执行的主线程。如果您的函数正在等待某个异步 API,那很好,主线程没有被阻塞。在您等待该 API 调用回调、解决承诺等时处理其他请求。但是,我认为真正的问题可能是您实际上在这里谈论 同步 代码 - 代码只是“计算数学”,可能需要足够长的时间才能成为问题。这是怎么回事?
-
Express 中间件被设计成能够异步执行。但是我认为您对异步是什么有很大的误解。 node.js 中的异步函数不一定在单独的线程中运行,更不用说线程池了。特别是如果该异步操作与网络相关
-
是的,我的中间件正在解密 JWT 并检查其签名的有效性。我只是担心这些过程可能是同步的。我使用“jsonwebtoken”库进行签名验证,但是对于解密,我使用的是@ronomon/crypto-async 库。 (见附录)。
-
slebetman,也许我不懂异步。那么,你是对的。如果异步代码不在单独的线程中,它将如何运行?我了解不需要线程池作为网络操作。使用操作系统调用,但不确定我是否理解 Node.js 是如何异步运行的。否则代码。
标签: javascript node.js express middleware