2015-12-21 62 views
0

我想確保用戶通過身份驗證(當登錄用戶獲取會話時)。安全的方法來檢查身份驗證(NodeJS/Express)

function isAuthenticated(req, res, next) { 

    // do any checks you want to in here 

    // CHECK THE USER STORED IN SESSION FOR A CUSTOM VARIABLE 
    // you can do this however you want with whatever variables you set up 
    if (req.user.authenticated) 
     return next(); 

    // IF A USER ISN'T LOGGED IN, THEN REDIRECT THEM SOMEWHERE 
    res.redirect('/'); 
} 
app.get('/hello', isAuthenticated, function(req, res) { 
    res.send('look at me!'); 
}); 

是否有另一種(更安全)的方式來檢查用戶是否通過身份驗證?

回答

3

使用express-session

https://github.com/expressjs/session

Psudo代碼:

var expressSession = require('express-session'); 
app.use(expressSession({ secret: 'secret' })); 

//...// 
app.get('/',function(req,res){ 
    if (req.session.auth === undefined || req.session.auth === false){ 
     //handle by redirection to authentication page 
    } 
    //user is authenitcated 
}); 
+0

什麼的'secret'選項? –

+0

會話通過在瀏覽器上設置cooky來工作。無論何時瀏覽重新確認,它都會將該cookie發送回服務器。 secred被用作處理cookie值的散列函數的關鍵字 –

+0

它是否像密碼? –