node.js - 如果 header 中不存在 JWT token ,如何执行某些逻辑?

标签 node.js jwt passport-jwt

我正在使用passport-jwt,并且有一个端点,如果 header 中不存在jwt token ,则该端点应该从数据库返回一些数据。 是否可以应用一些逻辑而不只是发送未经授权的 401?

router.get(
    '/get/items',
    passport.authenticate('jwt', {session: false}),
    (req, res) => {
     // reaches this point only after validating token
     ...
    }
);

因此,如果 jwt token 存在,基于它的端点应该返回一些数据。如果没有,则应返回数据库中的一些其他数据

最佳答案

我认为custom callback是一个选项。它作为最后一个参数传递给 authenticate(strategy, options,callback) 方法,它将允许您设置您想要的行为。

您的代码将如下所示:

app.get('/get/items', (req, res, next) => {

    passport.authenticate('jwt', { session: false }, (err, user, info) => {
        if (!user) {
            /* 
                Unauthorized accees.
                Handle here the request as u wish
            */

            /* Do some custom logic and return your desired result */
            return res.status(401).json({ success: false, message: 'Unauthorized access!' });
        }

        /* User is authorized. Do other stuff here and return your desired result*/
        return res.status(200).json({ success: true, message: 'Congratulations!' });
    })(req, res, next);
    
});

In this example, note that authenticate() is called from within the route handler, rather than being used as route middleware. This gives the callback access to the req and res objects through closure.

If authentication failed, user will be set to false. If an exception occurred, err will be set. An optional info argument will be passed, containing additional details provided by the strategy's verify callback.

The callback can use the arguments supplied to handle the authentication result as desired. Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response.

Source

关于node.js - 如果 header 中不存在 JWT token ,如何执行某些逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55813060/

相关文章:

node.js - 使用 Node JS 将 Excel 转换为 JSON

javascript - 在关闭文件流之前如何等待文件流完成写入?

asp.net - 使用 .net core Identity 和 JwtBearerAuthentication 授权策略属性总是返回 403 forbidden

ios - 必须提供 secret 或公钥 - IOS/Swift + Socket.io-JWT

asp.net-web-api2 - 在 Controller 操作中获取 JSON Web Token 有效负载数据

node.js - TypeError : Joi. 验证不是一个函数

javascript - 从连接到 Raspberry Pi 的两个 RFID RC522 读取器读取序列号、时间戳等数据

javascript - 在获取用户时使用 Passport-jwt 时未定义 req.user

javascript - 为什么我的应用程序没有到达 console.log?