护照本地策略不保存cookie或会话中的用户

我试图使用快递4护照,并通过本地策略进行validation。 我试图让一个简单的设置工作,但我有问题。

我尝试使用授权中间件function进行身份validation… deserializeUser永远不会被调用,req.user是未定义的,并且会话和cookie中缺less用户数据。 谁能帮我?

我的server.js文件:

var express = require('express'); var app = express(); var path = require('path') var port = process.env.PORT || 3000; var argv = require('minimist')(process.argv.slice(2)); var dust = require('express-dustjs') var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var methodOverride = require('method-override'); var authService = require('./app/services/auth.js') var dbConfig = require('./app/config.js')['documentDB']; var authService = require('./app/services/auth.js'); /* * DUST JS */ // Dustjs settings dust._.optimizers.format = function (ctx, node) { return node } // Define custom Dustjs helper dust._.helpers.demo = function (chk, ctx, bodies, params) { return chk.w('demo') } // Use Dustjs as Express view engine app.engine('dust', dust.engine({ // Use dustjs-helpers useHelpers: true })) /* * STATIC ASSETS */ app.use('/', express.static(__dirname + '/public')); app.set('view engine', 'dust') app.set('views', path.resolve(__dirname, './app/views')) app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser('X+a1+TKXwd26mkiUUwqzqQ==')); app.use(session({ secret: 'X+a1+TKXwd26mkiUUwqzqQ==', resave: true, saveUninitialized: true, cookie : { secure : true, maxAge : (4 * 60 * 60 * 1000) } })); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "http://localhost:8080"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-AUTHENTICATION, X-IP, Content-Type, Accept"); res.header("Access-Control-Allow-Credentials", true); res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); next(); }); // Configure Passport authenticated session persistence. // // In order to restore authentication state across HTTP requests, Passport needs // to serialize users into and deserialize users out of the session. The // typical implementation of this is as simple as supplying the user ID when // serializing, and querying the user record by ID from the database when // deserializing. passport.serializeUser(function(user, cb) { console.log('serializeUser : ', user); cb(null, user.id); }); passport.deserializeUser(function(id, cb) { console.log('-------------------------------'); console.log('-------------------------------'); console.log('deserializeUser : ', id); console.log('-------------------------------'); console.log('-------------------------------'); authService.getAccountByID(id, function (err, user) { if (err) { return cb(err); } cb(null, user); }); }); passport.use('local', new LocalStrategy({ usernameField: 'email', passwordField: 'password' }, function(username, password, callback) { authService.authenticate(username, password, function(err, user) { if (err) { console.log("ERR >> ", err); return callback(err, false, err); } return callback(err, user); }); }) ); app.use(passport.initialize()); app.use(passport.session()); app.use(methodOverride()); /* * ROUTES */ app.use('/', require('./app/routes/index.js')(passport)); app.use('/prototypes/', require('./app/routes/prototypes.js')); app.use('/auth', require('./app/routes/auth')(passport)); /* * APP START */ app.listen(port, function () { var msg = 'Express started > '; console.log('Express started >> '); console.log(' env: ', process.env.NODE_ENV); }).on('error', function(err){ console.log('ON ERROR >> '); console.log(err); }); process.on('uncaughtException', function(err) { console.log('ON UNCAUGHT EXCEPTION >>'); console.log(err); }); 

中间件function和路由。

 var express = require('express'); var router = express.Router(); var controller = require('../controllers/index.js'); module.exports = function(passport) { router.get('/', controller.index); router.get('/test', verifyAuth, function(req, res) { return res.status(200) .json({"req.isAuth" : req.isAuth}); }); return router; }; function verifyAuth(req,res,next) { console.log('req.cookies : ', req.cookies); console.log('req.login', req.login); console.log('req.isAuthenticated : ', req.isAuthenticated); console.log('req.session', req.session); console.log('req.user : ', req.user); if ( !req.isAuthenticated() ) { res.status( 400 ); // constant defined elsewhere, accessible here return res.end('Please Login'); // or a redirect in a traditional web app, } // as opposed to an SPA next(); } 

这里是login路由:router.post('/ login',function(req,res,next){

  passport.authenticate('local', function(err, user, info) { if (err || !user) { return res.send(500, info); } req.login(user, function(err) { if (err) { return next(err); console.log('ERROR > ', error); } return res.json(200, user); }); })(req, res, next); }); 

       

网上收集的解决方案 "护照本地策略不保存cookie或会话中的用户"

我相信你需要把护照逻辑放在app.post(); 不仅在app.use()

 app.post('/login', passport.authenticate('local', { failureRedirect: '/login' }), function(req, res) { res.redirect('/'); }); 

看看这个例子server.js在github上的护照组: Passport Example