表达,没有401认证

时间:2013-07-17 19:35:56

标签: node.js authentication express

这是关于身份验证方法的简历 我尝试使用express.basicAuth,但它强制浏览器询问用户并通过,我需要使用自己的登录页面,例如google,facebook yahoo ......

这是对的吗?有没有更好的办法呢?
如果可以的话,我想避免使用护照等模块。

我想使用这样的函数,使用auth中间件(app.get('/loggedin', auth, function(req, res)...)     var express = require('express');     var app = express();

app.use(express.cookieParser());
var RedisStore = require('connect-redis')(express);
app.use(express.session({
  store: new RedisStore({
    host: 'localhost',
    port: 6379,
    db: 2,
    pass: 'RedisPASS'
  }), secret: '1234567890QWERTY'
}));

var auth = function(req, res, next) {
    if (req.session.authStatus === 'loggedIn')
        next();
    else
        res.redirect('/login');
};

app.get('/', function(req, res) {
    console.log("/");
    res.send('not authenticate');
});

app.get('/signin', function(req, res) {
    console.log("/signin");
    if (req.body.user && req.body.pass)
    {
       req.user = req.body.user;
       req.remoteUser = req.body.user;
       req.session.authStatus = 'loggedIn';

       req.session.lastPage = '/signin';
       res.redirect('/loggedin');
    }
    else
       res.redirect('/login');
});

app.get('/loggedin', auth, function(req, res) {
    if(req.session.lastPage) {
        res.write('Last page was: ' + req.session.lastPage + '. ');
    }

    req.session.lastPage = '/loggedin';
    res.write('Yeeeeeeeeeee');
    res.end();
});


app.get('/loggedin2', auth, function(req, res) {
    console.log("/loggedin2");
    if(req.session.lastPage) {
        res.write('Last page was: ' + req.session.lastPage + '. ');
    }

    req.session.lastPage = '/loggedin2';
    res.write('WoWWWWW!!!!!!');
    res.end();
});

app.get('/logout', auth, function(req, res) {
    console.log("/logout");
    req.session.destroy();
});

app.get('/login', function(req, res) {
    console.log("/notlogged");
    res.send('enter user and pass...');
});

app.listen(process.env.PORT || 8080);

1 个答案:

答案 0 :(得分:0)

您可以在npm中使用passport中间件模块 - passport-local模块提供针对本地资源(如数据库)的身份验证。