2016-06-11 98 views
0

我想使用passport localStrategy在我的NodeJs Web應用程序中創建非常簡單的認證。NodeJs護照本地策略認證

app.post('/login', function(req, res) { 
    console.log('before auth'); 
    passport.authenticate('local'), 
    function(req, res) { 
     // If this function gets called, authentication was successful. 
     // `req.user` contains the authenticated user. 
     // res.redirect('/users/' + req.user.username); 
     console.log('auth is ok'); 
    } 
}); 

我所做的:

  1. 我有網頁形式域登錄名和密碼與行動=「/登錄」

  2. 在我的應用路由器我有路線登錄像這樣

表單提交後,我可以看到我的控制檯「auth」之前,這意味着臨時t路由器正在工作。但我不能看到「身份驗證是好的」,這意味着身份驗證沒有成功。

如何在我的應用程序中實現passport.authenticate函數?

+0

也許你應該從[示例代碼](https://github.com/passport/express-4.x-local-example)開始。 – robertklep

+0

@robertklep謝謝。你的例子正在爲我工​​作。我會嘗試比較你和我的代碼,並嘗試找到我的錯在哪裏... –

+0

@robertklep你能告訴我,如果你給我們的鏈接是什麼,當作者使用'cb'時,我可以替代「完成」一詞。文檔中使用了'done'。我想知道'done'和'cb'是否可以互換 –

回答

0
var passport = require('passport'); 
var LocalStrategy = require('passport-local').Strategy; 

    passport.use(new LocalStrategy({ 
    usernameField: 'email', 
    passwordField: 'password' 
    }, function(email, password, next) { 
    //do what you want here 
    //call next(pass parameter here (i.e error, object) 
    })); 


app.post('/login', function(req, res) { 
     console.log('before auth'); 
     passport.authenticate('local', function(err, anotherthing){ 
     //err and anotherThing are the parameters send by strategy (next function). 

     }); 
    }); 

也看看here。欲瞭解更多細節,請完成此項。親切的問候

+0

對不起,我的問題還不夠清楚。我需要一些幫助來實施本地戰略實施。換句話說,爲了在我的Web應用程序中驗證用戶,我必須做些什麼? –

+0

@AlexZhulin我已更新答案,以幫助您瞭解如何實施戰略。還發布了鏈接到另一個主題的鏈接來幫助你。 –

+0

我添加passport.use(新localStrategy({ usernameField: '電子郵件', passwordField: 'passwd文件' }, 功能(用戶名,密碼,下一次){ 的console.log( 'LocalStrategy');接下來 ( ); } ));正如你所建議的,但似乎代碼的和平沒有被調用,因爲我不能在我的日誌「LocalStrategy」消息中看到......你能提出我的錯在哪裏嗎?在此先感謝 –