if (!options.algorithms) throw new Error('algorithms should be set'); 错误:应该设置算法

Shu*_*pta 43 javascript node.js npm express-jwt

我开始学习 Nodejs,但我被困在了中间。我从 npm 安装了一个新库,它是express-jwt,运行后显示某种错误。附上错误的代码和日志,请大家帮帮忙!

const jwt = require('jsonwebtoken');
require('dotenv').config()
const expressJwt =  require('express-jwt');
const User = require('../models/user');




exports.requireSignin =  expressJwt({ secret:  process.env.JWT_SECRET});
Run Code Online (Sandbox Code Playgroud)

下面是错误的日志。

[nodemon] starting `node app.js`
D:\shubh\proj\Nodejs\nodeapi\node_modules\express-jwt\lib\index.js:22
  if (!options.algorithms) throw new Error('algorithms should be set');
                           ^

**Error: algorithms should be set**
    at module.exports (D:\shubh\proj\Nodejs\nodeapi\node_modules\express-jwt\lib\index.js:22:34)
    at Object.<anonymous> (D:\shubh\proj\Nodejs\nodeapi\controllers\auth.js:64:26)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
 
Run Code Online (Sandbox Code Playgroud)

Tug*_*lik 79

您应该将 algorithm 属性添加到 jwt 构造函数。

例子;

expressJwt({ secret:  process.env.JWT_SECRET, algorithms: ['RS256'] });
Run Code Online (Sandbox Code Playgroud)

  • 它根据用途而变化,如果你想将它用于会话,你可以使用 HSXXX 类型。如果您想将其用于跨应用程序身份验证(如 oauth)等,您可以更喜欢 RSXXX 类型。RS 类型是数字签名,HS 类型不是。 (7认同)
  • @Shubhamgupta我建议您阅读本文以更好地理解两种算法之间的区别:/sf/answers/2746757681/ (2认同)

小智 27

由6.0.0 版本更改引起的问题。 文档最近也更新了,它说:

当提供第三方库作为机密时,需要算法参数来防止潜在的降级攻击。

所以现在指定算法属性是强制性的,如下所示:

expressJwt({
  secret: 'secret',
  algorithms: ['HS256']
})
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你 - 我在文档中看到“HS256”是默认算法,所以我很困惑为什么需要指定它。原来 npm 上的文档还没有更新。 (4认同)