2013-04-15 54 views
3

我正在嘗試使用express在node.js服務器上設置通行證本地身份驗證。它似乎應該是非常簡單的。但我陷入困境。快速身份驗證重定向導致無限循環

這兩個片段做工精細在一起:

app.get('/', ensureAuthenticated, function(req, res){ 
    res.redirect('/index.html', { user: req.user }); 
}); 

app.post('/login', 
    passport.authenticate('local', { failureRedirect: '/login.html', failureFlash: true, successFlash: "Success!" }), 
    function(req, res) { 
    res.redirect('/'); 
}); 

的問題是沒有什麼讓我打字「www.myurl.com/index.html」到地址欄和右側拖放到我的網頁。

如果我使用一個像這樣的任何代碼:

app.get('/index.html', ensureAuthenticated, function(req, res){ 
    res.redirect('/index.html', { user: req.user }); 
}); 

好像我陷入一個循環......這將是很好,如果它可以檢查我的身份驗證和送我對我的方式,而不永遠檢查每個重定向。避免這種情況的方法是什麼?

我注意到文檔似乎利用.render而不是重定向。但是這個SEEMS要​​求我使用.ejs,我寧願不這樣做。這是必須的嗎?

++僅供參考++

function ensureAuthenticated(req, res, next) { 
    if (req.isAuthenticated()) { return next(); } 
    res.redirect('/login.html') 
} 

回答

2

所以我猜你是讓express.static()處理請求index.htmllogin.html?在這種情況下,你可以創建index.html的路線,將首先檢查認證,並採取相應的行動:

app.get('/index.html', ensureAuthenticated, function(req, res, next) { 
    // if this block is reached, it means the user was authenticated; 
    // pass the request along to the static middleware. 
    next(); 
}); 

請確保您添加express.static到中間件堆棧之前上述航線聲明,否則將被繞過(Express中間件/路由按聲明順序調用,第一個與請求相匹配的將處理它)。

編輯:我總是忘記,這是可能的,而且更清潔,太:

app.use('/index.html', ensureAuthenticated); 

(而不是以上app.get

+0

我已經結束了做app.get('/ index.html',ensureAuthenticated);到目前爲止它工作正常。是否有理由使用「使用」而不是「獲得」? – Jeremythuff

+0

我傾向於將'app.use'用於'真正'中間件,就像我的示例代碼中一樣。此外,'app.use'將匹配GET以外的請求方法,但在這種情況下,這不是真正的問題。因此,除了語義之外,在這種情況下,沒有理由選擇另一個:)(編輯:使用'app.get'也可能存在潛在的副作用,因爲它由路由器中間件處理,但我不認爲他們也會在這裏申請) – robertklep

1

你爲什麼要使用重定向每一個途徑嗎?所有你需要做的是

app.get('/',ensureAuthenticated,function(req,res){ 

// your route logic goes here 

}); 

的ensureAutheticated會檢查你的代碼是否已經驗證過了。不需要每次通過登錄路由重定向它。

res.renderres.redirect()是用於不同目的的不同的東西。

重定向重定向到爲res.render() 渲染view.The視圖可以通過它,你必須,如果你與快遞的最新版本使用什麼consolidate.js任何文件supported的路線。

因此,從您的路由中刪除所有這些重定向,無限循環應該停止。您只需傳遞ensureAuthenticated以確保請求已通過身份驗證。