快递3.0和护照认证

时间:2012-07-13 15:25:33

标签: node.js authentication express passport.js

我正在使用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,并且调试中没有req.user变量。

快递3和护照互动是否有问题或我做错了什么?

4 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

问题在于我使用curl -L -d "name=Test&password=1"进行测试,而curl -L无法正常工作。但它适用于网络浏览器。

答案 3 :(得分:0)

我多年来一直在努力解决这个问题。为我修复的是更改会话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

相关问题