为什么我的经过认证的NodeJS路由返回一个不正确的JWT令牌的结果?



我有一个NodeJS应用程序,由于原来的应用程序变得有点臃肿,我已经开始把它分成更小的文件。

在我的index.js中,我有一个由自由职业者编写的函数保护的路由,该函数提供JWT认证。这些路由按要求工作。

app.use(require('./lib/api-calls/convert.js'));
//  Security Enabled index.js
//
const { app } = require ('./lib/deps/init_dependencies.js');
const { enableSecurity } = require("./security");
const main = async () => {
    // Enable API JWT Security = Comment out the line below to turn off security.
    await enableSecurity(app);
        
    app.get('/v1/createSession:key/:limit', function (req, apiResponse) {
        
       // My route, working well
    });
}
main()

我已经创建了/lib/routes/convert.js,我想在这个文件中编写新的路由,也需要JWT身份验证。然而,我总是收到状态200 'OK',无论身份验证头是否正确…我在用邮差打电话。下面是我的代码:

const app = require('express')();
    
//JWT authentication
const { enableSecurity } = require('../../security');
const main = async () => {
    // Enable API JWT Security = Comment out the line below to turn off security.
    await enableSecurity(app);
    app.get('/v3/convertw3w/:locationValue/:countryCode', function (req, res) {
        
        res.status(200).send({ status: 'OK' });
    });
}
main()
module.exports = app;

有人能发现问题吗?我昨晚花了很长时间在这上面!

感谢

这里有一些值得思考的东西我们做了类似的事情,但是如果你使用

enableSecurity(app)

作为路由上的中间件和

next()

函数,你可以省略这个承诺,因为中间件被设计成按照中间件的顺序进行处理,而下一个函数告诉express移动到下一个中间件。

我们如何做到这一点,是有中间件'auth',因为中间件将传递请求和res对象到堆栈中的每一个,你可以把所有的JWT解码在一个地方。

我们通常会在header中传递token或者在req对象中传递token,这取决于我们传递的mime类型,所以在out auth中我们检查token是否在header中或者在req中,如果在则解码,如果通过解码则传递

next()

,否则我们将返回。json({"response":"not authorized"})

相关内容