2012-07-13 112 views
4

我使用[email protected][email protected]並使用本地策略進行身份驗證。express 3.0和護照認證

一切似乎很好地工作,並重定向的成功與失敗正確

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和護照互動有問題還是我做錯了什麼?

回答

0

authenticate()是中間件。從文檔:

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

這是使用它的sipmlest方式,它改變不了什麼。如果req.isAuthenticated()爲false,我仍然在'/'路徑上添加ensureAuthenticated(如果req.isAuthenticated()爲false,則重定向到'/ login'),但由於req.isAuthenticated()始終爲false,所以出現錯誤路由。 – Yuri 2012-07-13 16:31:48

+0

哦,不!實際上現在是這樣,但我仍然在錯誤的重定向 app.get('/ profile',ensureAuthenticated,routes.profile); – Yuri 2012-07-13 16:38:18

+0

是的,不要把ensureAuthenticated放在/ login路徑中。並在您的ensureAuthenticated函數重定向到/登錄。 – jabbermonkey 2012-07-13 16:40:32

0

的問題是,我與curl -L -d "name=Test&password=1"測試,並curl -L如我所料不工作。但它在網絡瀏覽器中工作得很好。

+0

如果您的發佈數據是真的'名稱:測試和密碼:1'那麼這也難怪它沒有工作。它必須是'name = Test&password = 1'。 – kay 2012-07-16 01:00:00

+0

當然,這是有效的請求。我只是在這裏誤拼了。 – Yuri 2012-07-19 10:43:16

1

我也有類似的問題,但事實證明,這是因爲我使用快速會議,而沒有爲會話數據指定數據存儲。這意味着會話數據被存儲在RAM中,並且由於我使用多個工作人員,會話存儲不在工作人員之間共享。我重新配置了我的快速會話,使用RedisStore代替,並且isAuthenticated()開始按預期返回true。

app.use express.session 
    secret: '...' 
    store: new RedisStore 
     host: redisUrl.hostname 
     port: redisUrl.port 
     db: ... 
     pass: ... 
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()返回真