req.isAuthenticated返回false(护照与express.js)

时间:2015-03-18 11:49:37

标签: javascript authentication express request passport.js

我使用带有快递框架的护照,但在使用POST登录后,req.isAuthenticated始终返回false ...

登录后应显示图像(如果用户已登录,则应该可以访问图像)。

服务器:



var express = require('express')
  , passport = require('passport')
  , flash = require('connect-flash')
  , LocalStrategy = require('passport-local').Strategy;
var path = require('path');
var app = express();   

var users = [
    { id: 1, username: 'bob', password: 'secret', email: 'bob@example.com' }
  , { id: 2, username: 'joe', password: 'birthday', email: 'joe@example.com' }
];

function findById(id, fn) {
  var idx = id - 1;
  if (users[idx]) {
    fn(null, users[idx]);
  } else {
    fn(new Error('User ' + id + ' does not exist'));
  }
}

function findByUsername(username, fn) {
  for (var i = 0, len = users.length; i < len; i++) {
    var user = users[i];
    if (user.username === username) {
      return fn(null, user);
    }
  }
  return fn(null, null);
}

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

passport.deserializeUser(function(id, done) {
  findById(id, function (err, user) {
    done(err, user);
  });
});

passport.use(new LocalStrategy(
  function(username, password, done) {
    process.nextTick(function () {
      findByUsername(username, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
        if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
        return done(null, user);
      })
    });
  }
));

app.configure(function() {
  app.use(express.logger());
  app.use(express.cookieParser('keyboard cat'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(flash());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use('/media', ensureAuthenticated); //commenting this out and it work...
  app.use('/media', express.static(path.join(__dirname, 'media')));
});

app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
  function(req, res) {
    console.log(req.sessionID);
    console.log('login success');
    res.send('ok');
  }
);

app.listen(3000, function() {
  console.log('Express server listening on port 3000');
});

function ensureAuthenticated(req, res, next) {
  console.log(req.isAuthenticated());
  console.log(req.sessionID);
  if (req.isAuthenticated()) { return next(); }
  res.status(500).send();
  // res.redirect('/login')
}
&#13;
&#13;
&#13;

HTML的文件:

&#13;
&#13;
<html>
<head>
	<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="js/socket.io.js"></script>
</head>
<body>
	<img src="" id="testimage" />
	<img src="" id="testimage2" />

	<script>
	    	$.post('http://localhost:3000/login', {
	    		username: 'bob',
	    		password: 'secret'
	    	});

	      setTimeout(function() {
		    $('#testimage').attr("src","http://localhost:3000/media/01.jpg");
	      },2000);
	      setTimeout(function() {
		    $('#testimage2').attr("src","http://localhost:3000/media/02.jpg");
	      },5000);
	</script>
</body>
</html>
&#13;
&#13;
&#13;

我坐了好几个小时但却找不到问题......我做错了什么?

编辑:我发现,每个请求的sessionId(req.sessionId)都不同。我修改了html文件以加载两张图片,两个请求的sessionid也不同。添加res.status(500).send();为了确保经过验证的方法,两个请求的sessionId是相同的,但它与/ login post请求的sessionId不同... 我修改了上面的代码......

Edit2:发现app.post(...)总是创建新的sessionID,app.get(...)使用相同的sessionID ...为什么?

1 个答案:

答案 0 :(得分:0)

您是如何为HTML服务的?如果它不是通过相同的node.js服务那么那可能是你的问题。

我尝试添加一个get(&#39; /&#39;)路由,使用ejs呈现HTML,一切正常。我将您的html文件重命名为根项目目录中的index.ejs,并对您的代码进行了以下更改:

app.configure(function() {
    app.use(express.logger());
    app.use(express.cookieParser('keyboard cat'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.session({
        secret: 'keyboard cat'
    }));
    app.use(flash());
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(app.router);
    app.use('/media', ensureAuthenticated); //commenting this out and it work...
    app.use('/media', express.static(path.join(__dirname, 'media')));

    // Add EJS rendering
    app.set('views', __dirname);
    app.set('view engine', 'ejs');
});

app.get('/', function(req, res) {
    res.render('index');
});