【问题标题】:express 3.0 and passport authenticationexpress 3.0和护照认证
【发布时间】:2012-07-13 11:34:54
【问题描述】:

我正在使用 express@3.0.0beta4 和 passport@0.1.12,并使用本地策略进行身份验证。

一切似乎都运行良好,并且正确地重定向成功和失败

app.post('/login', passport.authenticate('local', { failureRedirect: '/' }),
function(req, res) {
  console.log(req.isAuthenticated()); // true
  res.redirect('/users/' + req.user.id );
});

但是如果我在配置文件路由上添加 ensureAuthenticated

app.get('/users/:id', ensureAuthenticated, routes.user);

function ensureAuthenticated(req, res, next) {
  console.log(req.isAuthenticated()); // false
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/');
}

登录后它会将我重定向回“/”(即登录页面)而不是“/users/id”(用户配置文件)。问题是 req.isAuthenticated() 总是返回 false 并且 debug 中没有 req.user 变量。

是express 3和passport交互有问题还是我做错了什么?

【问题讨论】:

    标签: node.js authentication express passport.js


    【解决方案1】:

    我也遇到了类似的问题,但事实证明这是因为我使用的是快速会话而没有为会话数据指定数据存储。这意味着会话数据存储在 RAM 中,并且由于我使用多个工作人员,因此工作人员之间不共享会话存储。我将我的快速会话重新配置为使用 RedisStore,而 isAuthenticated() 开始按预期返回 true。

    app.use express.session
        secret: '...'
        store: new RedisStore
          host: redisUrl.hostname
          port: redisUrl.port
          db: ...
          pass: ...
    

    【讨论】:

      【解决方案2】:

      authenticate() 是中间件。来自文档:

      app.post('/login', 
        passport.authenticate('local', { failureRedirect: '/login' }),
        function(req, res) {
          res.redirect('/');
        });
      

      【讨论】:

      • 这是最简单的使用方式,并且没有任何改变。仍然如果我在“/”路由上添加 ensureAuthenticated(如果 req.isAuthenticated() 为假,则重定向到“/login”)我的路由错误,因为 req.isAuthenticated() 始终为假。
      • 哦,不!实际上现在是真的,但我在 app.get('/profile', ensureAuthenticated, routes.profile); 中仍然有错误的重定向;
      • 是的,不要将 ensureAuthenticated 放在 /login 路径中。并在您的 ensureAuthenticated 函数中重定向到 /login.
      • 我已更改代码并突出显示问题。所以我需要 /users/id 在没有身份验证的情况下不可用,所以我使用 ensureAuthentication 中间件保护路径 /users/id,结果是 - 我无法登录到配置文件 /users/id
      【解决方案3】:

      问题是我用curl -L -d "name=Test&password=1"curl -L 测试它没有按预期工作。但它适用于网络浏览器。

      【讨论】:

      • 如果您的帖子数据真的是name:Test&password:1,那么它不起作用也就不足为奇了。必须是name=Test&password=1
      • 当然,这是有效的请求。我只是在这里打错了。
      【解决方案4】:

      我也为这个问题苦苦挣扎了很久。为我解决的问题是更改会话 cookie 的 maxAge 属性 - 之前它太低了:

      app.use(express.cookieParser()); 
      app.use(express.session({
        secret: config.session.secret,
        cookie: {
          maxAge: 1800000, //previously set to just 1800 - which was too low
          httpOnly: true
        }
      }));
      

      在此更改后,req.isAuthenticated() 返回 true

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-05
        • 2015-09-23
        • 2019-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多