Passport本地策略未将用户保存在cookie或会话中

时间:2016-03-28 20:57:58

标签: javascript node.js session express passport.js

我正在尝试使用快递4的护照并使用本地策略进行身份验证。我试图让一个简单的设置工作,但我有问题。

我尝试使用授权中间件功能进行身份验证...从不调用deserializeUser,未定义req.user并且会话和cookie都缺少用户数据。任何人都可以帮助我吗?

我的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);
});

中间件功能和路由。

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

这是登录路线:     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);

});

1 个答案:

答案 0 :(得分:2)

我认为您需要将护照逻辑放在app.post(); app.use()中{/ 1}}:

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

在github上查看这个示例server.js组成护照团队: Passport Example