简体   繁体   English

Node.js / express - 使用带有redis的护照,使会话未经授权

[英]Node.js / express - using passport with redis, getting session unauthorized

I'm trying to use redis with express to create a user login and session. 我正在尝试使用redis with express来创建用户登录和会话。 I test the route using this curl script: 我使用这个curl脚本测试路由:

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

When I do this, passport works fine through serialization, and then it returns http 302. I haven't figured out what it does after serialization, but when I try it in the browser with my login html form instead of curl, It shows me "Unauthorized" 401, and I don't see any of my console logs. 当我这样做,护照通过序列化工作正常,然后它返回http 302.我没有弄清楚序列化后它做了什么,但当我在浏览器中使用我的登录html表单而不是curl尝试它时,它显示我“未经授权”401,我没有看到任何控制台日志。 Here's my app.js: 这是我的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);
});

And the session POST route: 会话POST路由:

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

I could only really find examples of passport with mongodb, so I'm not sure about the following. 我只能找到mongodb护照的例子,所以我不确定以下情况。 I attempt to find a user, but I'm not sure about the callbacks or what passport is doing with the user info when I return done: 我试图找到一个用户,但是当我回来时,我不确定回调或护照用户信息做了什么:

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 serialization: 护照序列化:

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
})

Why does this act differently with a browser than with curl? 为什么这与浏览器的行为不同而不是curl? Any help or comments much appreciated! 任何帮助或评论非常感谢!

Figured it out! 弄清楚了! To use passport with any database (not just mongo), I would recommend trying it with a dummy user first. 要将护照与任何数据库(不仅仅是mongo)一起使用,我建议首先尝试使用虚拟用户。 Here's what I did. 这就是我做的。

Login Form (login.html): 登录表单(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> 

Routing (route.js): 路由(route.js):

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

Passport Local Strategy setup (passport.js): 护照本地策略设置(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);
})

Although I'm wondering if it's necessary to find user in my database twice, or if I'm using deserialize incorrectly. 虽然我想知道是否有必要在我的数据库中找到两次用户,或者我是否正在使用反序列化错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM