【问题标题】:Do I need to authenticate session data in Express middleware?我需要在 Express 中间件中验证会话数据吗?
【发布时间】:2013-06-27 09:21:44
【问题描述】:

目前,我的 Express 3.0 应用的身份验证中间件如下所示:

return function (req, res, next) {
    if (!isProtected(req.path)) {
        debug('Allowed path "' + req.path + '" -->  calling next()');
        next();
    } else if (req.session.user != undefined) {
        debug('User session detected --> calling next()');
        next();
    } else if (req.cookies.user != undefined && req.cookies.pass != undefined) {
        var username = req.cookies.user;
        var hash = req.cookies.pass;

        debug('Cookies detected, authorizing...');
        dbman.auth(username, hash, function (err, record) {
            if (err) debug('Authorization error --> ' + err);
            else if (!record) res.redirect(redirectPath);
            else {
                debug('Autologin successful, storing session data');
                req.session.user = record;
                next();
            }
        });
    } else {
        debug('Protected path -- No valid session or cookies were detected');
        debug('redirecting to "' + redirectPath + '"');
        res.redirect(redirectPath);
    }
};

我的工作假设用户永远无法自己设置req.session,而req.session.user 只有在成功验证后才会设置。因此,如果会话存储中存在用户记录,我会让请求通过,甚至无需验证记录中存在的用户详细信息。但是,当有 cookie 时,我会验证 cookie 中存在的哈希值。我是否需要对会话记录进行身份验证,以免用户以某种方式操纵会话?

【问题讨论】:

    标签: node.js session express middleware


    【解决方案1】:

    Session 只是您的内部数据结构 - 所以不,除非您为会话操作提供逻辑,否则用户无法做到这一点。 Express 所做的是将加密的会话 ID 存储在用户 cookie 中,然后将其转换为存储在服务器上的会话对象。用户只有在知道加密密钥的情况下才能操作会话对象 ID——他不知道。

    【讨论】:

      猜你喜欢
      • 2017-03-19
      • 2023-03-12
      • 1970-01-01
      • 2015-08-14
      • 2019-07-03
      • 2015-12-25
      • 1970-01-01
      • 2022-09-25
      • 2020-03-04
      相关资源
      最近更新 更多