我正在尝试将redis与express一起使用来创建用户登录名和 session 。我使用以下curl脚本测试路由:

curl -d 'email=testEmail&password=testPass' http://localhost:3000/users/session

当我这样做时, Passport 可以通过序列化很好地工作,然后返回http302。序列化后我还没有弄清楚它的作用,但是当我在浏览器中使用登录html形式而不是curl尝试它时,它显示了我“未经授权” 401,并且我看不到任何控制台日志。这是我的app.js:
var express = require('express')
    , fs = require('fs')
    , cons = require('consolidate')
    , http = require('http')
    , flash = require('connect-flash')
    , passport = require('passport')
    , RedisStore = require( "connect-redis" )(express) //for sessions (instead of MemoryStore)
    , redis = require('redis')
    , env = process.env.NODE_ENV || 'development'
    , config = require('./config/config')[env]
    , db = redis.createClient(config.db.port, config.db.host);

db.select(config.db.users)
db.auth(config.db.auth);

var app = express();

//require passport strategies (see code block below)
require('./config/passport')(passport, config, app)

app.use('/assets', express.static(__dirname + '/public'));
app.use('/', express.static(__dirname + '/'));
app.set('views', __dirname + '/views');
app.set('view engine', 'html');

app.configure(function(){
    app.set('config', config);
    app.set('db', db);
    app.set('port', process.env.PORT || 3000);
    app.engine('.html', cons.swig);
    app.use(express.logger('dev'))
    app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
    app.use(express.cookieParser())
    app.use(express.bodyParser()) //enables req.body
    app.use(express.methodOverride()) //enables app.put and app.delete (can also just use app.post)
    app.use(express.session({
        secret: 'topsecret',
        cookie: {secure: true, maxAge:86400000},
        store: new RedisStore({
            client:db,
            secret:config.db.auth
        })
    }));

    app.use(flash())
    app.use(passport.initialize())
    app.use(passport.session())
    app.use(app.router)
});

// Bootstrap routes
require('./config/routes')(app, passport);

http.createServer(app).listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port')+', mode='+env);
});

和 session POST路线:
app.post('/users/session', passport.authenticate('local', {successRedirect: '/', failureFlash: 'Invalid email or password.', successFlash: 'Welcome!'}), users.session);

我只能在mongodb上找到 Passport 的示例,因此我不确定以下内容。我试图找到一个用户,但是我不确定回叫或返回用户名时 Passport 对用户信息的处理方式:
passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' },
    function(email, password, done) {

        var db = app.get('db')
        var multi = db.multi();

        db.get('email:'+email, function(err, uid){
            if (err) { console.log(err); return err }
            if (!uid) { console.log('no uid found'); return null }

            console.log('found '+uid)
            db.hgetall('uid:'+uid, function(err, user){
                if (err) { console.log(err); return err }
                if (!user) {
                    console.log('unkwn usr')
                    return done(null, false, { message: 'Unknown user' })
                }

                if (password != user.password) {
                    console.log('invalid pwd')
                    return done(null, false, { message: 'Invalid password' })
                }
                console.log('found user '+user) //I see this fine with curl, but no logs with browser
                return done(null, user)
            });
        });
    }
))

Passport 序列化:
passport.serializeUser(function(user, done) {
    console.log('passport serializing...'+user.name)
    done(null, user.name) //no idea what happens to it after this. returns a 302 with curl, and 401 with browser
})

为什么浏览器的行为与curl的行为不同?任何帮助或意见,不胜感激!

最佳答案

弄清楚了!要将 Passport 用于任何数据库(不仅是mongo),我建议您先与虚拟用户一起尝试。这就是我所做的。

登录表单(login.html):

<form method="post" action="http://localhost:3000/users/session" name="loginform">
    <input id="login_input_username" type="text" name="email" />
    <input id="login_input_password" type="password" name="password" autocomplete="off" />
    <input type="submit"  name="login" value="Submit" />
</form>

路由(route.js):
app.post('/users/session', passport.authenticate('local'),
    function(req, res){
        res.end('success!');
    });

Passport本地策略设置(passport.js):
passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' },
    function(email, password, done) {
        //find user in database here
        var user = {id: 1, email:'test', password:'pass'};
        return done(null, user);
    }
));

passport.serializeUser(function(user, done) {
    //serialize by user id
    done(null, user.id)
});

passport.deserializeUser(function(id, done) {
    //find user in database again
    var user = {id: 1, email:'test', password:'pass'};
    done(null, user);
})

尽管我想知道是否有必要在数据库中两次查找用户,或者我是否使用了不正确的反序列化。

关于Node.js/Express-将 Passport 与Redis一起使用,以使 session 未经授权,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15627358/

10-14 04:32