检查身份验证的安全方式(NodeJS / Express)

时间:2015-12-21 16:02:00

标签: javascript node.js 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!');
});

是否有其他(更安全)的方法来检查用户是否经过身份验证?

1 个答案:

答案 0 :(得分: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
});