2013-12-23 60 views
31

使用Passport.js有沒有辦法讓我爲相同的路由指定多個身份驗證提供程序?passport.js與多個身份驗證提供程序?

例如(從護照指南)我可以在下面的示例路線上使用本地和Facebook和Twitter策略?

app.post('/login', 
    passport.authenticate('local'), /* how can I add other strategies here? */ 
    function(req, res) { 
    // If this function gets called, authentication was successful. 
    // `req.user` contains the authenticated user. 
    res.redirect('/users/' + req.user.username); 
    }); 
+0

你爲什麼希望多策略混合成一條路由後? – damphat

回答

52

護照的中間件是建立在一個方式,讓您在一個passport.authenticate(...)調用中使用多種策略。

但是,它是用OR順序定義的。這就是說,如果沒有一種策略能夠成功,它將會失敗。

這是你將如何使用它:

app.post('/login', 
    passport.authenticate(['local', 'basic', 'passport-google-oauth']), /* this is how */ 
    function(req, res) { 
     // If this function gets called, authentication was successful. 
     // `req.user` contains the authenticated user. 
     res.redirect('/users/' + req.user.username); 
}); 

換句話說,順便用它,是傳遞一個包含你希望用戶進行身份驗證策略的名稱的數組。

此外,不要忘記以前設置你想實施的策略。

可以確認以下github上的文件這個信息:

Authenticate using either basic or digest in multi-auth example.

Passport's authenticate.js definition

+0

非常好!感謝您的幫助,這正是我一直在尋找的! – cgiacomi

+1

如何判斷最終用於認證用戶的認證策略?我當然可以爲每個策略使用不同的端點,但我試圖避免它。 –

+0

@asafam據我記憶,req.user保存登錄策略使用的信息。將不得不檢查tho ....會話中使用的大部分信息(後)保存在req對象 –

相關問題