简体   繁体   中英

req.isAuthenticated returning false (passport with express.js)

I'm using passport with express framework, but after login using POST the req.isAuthenticated always returns false...

After login an image should be shown (image should be accessible if user is logged in).

Server:

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

HTML-File:

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

I'm sitting for hours but can't find the problem... What am I doing wrong?

Edit: I found out, that the sessionId (req.sessionId) is different for each request. I modified the html file to load two pictures, also the sessionid of both requests are different. After adding res.status(500).send(); to ensureAuthenticated method the sessionId of both requests is the same, but it's different to the sessionId of the /login post request... I modified the code above...

Edit2: Found out that app.post(...) always creates new sessionID, app.get(...) uses same sessionID... Why?

How are you serving your HTML? If its not via the same node.js service then that might be your problem.

I tried adding a get('/') route that renders your HTML using ejs and everything is working fine for me. I renamed your html file to index.ejs in the root project dir and made the following changes to your code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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