req.session.passport为空:req.user未定义

我之前曾经问过类似的问题,但我注意到它是在Javascript部分。 对于现在可能会出现什么问题,我也有更具体的想法。

基本上,我的日志中req.session.passport是空的。 每当我开始浏览我的网站,req.user变得未定义,因为会话没有Passport的login用户了。

我想知道有没有人知道如何解决这个问题? 也许这只是Passport的configuration错误,或整个Express设置?

App.js:

var express = require("express"), bodyParser = require("body-parser"), mongodb = require("mongodb"), mongoose = require("mongoose"), uriUtil = require("mongodb-uri"), morgan = require("morgan"), session = require("express-session"), passport = require("passport"), flash = require("connect-flash"), ip = "hidden", port = process.env.PORT || 80 var app = express() app.disable("x-powered-by") app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use(morgan("dev")); // log every request to the console // required for passport app.use(session({ secret: "hidden", key: 'asdasdasd', cookie: { maxAge: 60000, secure: false }, resave: true, saveUninitialized: false })); // session secret app.use(passport.initialize()); app.use(passport.session()); // persistent login sessions app.use(flash()); // use connect-flash for flash messages stored in session app.set("view engine", "jade") app.use(express.static(__dirname + "/views")) require("./includes/passport")(passport) require("./includes/subject") require("./includes/user") 

Passport.js:

 var LocalStrategy = require("passport-local").Strategy, User = require("./user"), bCrypt = require('bcrypt-nodejs') module.exports = function(passport) { // used to serialize the user for the session passport.serializeUser(function(user, done) { done(null, user._id); }); // used to deserialize the user passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); // ========================================================================= // LOCAL SIGNUP ============================================================ // ========================================================================= // we are using named strategies since we have one for login and one for signup // by default, if there was no name, it would just be called "local" passport.use('signup', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField : "email", passwordField : "password", passReqToCallback : true // allows us to pass back the entire request to the callback }, function(req, email, password, done) { // asynchronous // User.findOne wont fire unless data is sent back process.nextTick(function() { // find a user whose email is the same as the forms email // we are checking to see if the user trying to login already exists User.findOne({ "email" : email }, function(err, user) { // if there are any errors, return the error if (err) return done(err); // check to see if theres already a user with that email if (user) { return done(null, false, req.flash("message", "Dit e-mail-adres is al bezet")); } else { // if there is no user with that email // create the user var newUser = new User(); // set the user's local credentials newUser.email = email; newUser.password = createHash(password); newUser.firstname = req.param('firstname'); newUser.lastname = req.param('surname'); newUser.year = parseInt(req.param('year')); newUser.study = req.param('study'); newUser.courses = req.param('courses'); newUser.phone = req.param('phone'); newUser.availability = req.param('availability'); newUser.description = req.param('descText'); // save the user newUser.save(function(err) { if (err) throw err; return done(null, newUser); }); } }); }); })); // ========================================================================= // LOCAL LOGIN ============================================================= // ========================================================================= // we are using named strategies since we have one for login and one for signup // by default, if there was no name, it would just be called 'local' passport.use("login", new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField : "email", passwordField : "password", passReqToCallback : true // allows us to pass back the entire request to the callback }, function(req, email, password, done) { // callback with email and password from our form // find a user whose email is the same as the forms email // we are checking to see if the user trying to login already exists User.findOne({ "email" : email }, function(err, user) { // if there are any errors, return the error before anything else if (err) return done(err); // if no user is found, return the message if (!user) { console.log('No user found with email ' + email) return done(null, false, req.flash('message', 'Gebruiker niet gevonden')); // req.flash is the way to set flashdata using connect-flash } if (!isValidPassword(user, password)){ console.log('Incorrect Password'); return done(null, false, req.flash('message', 'Onjuist wachtwoord')); // redirect back to login page } // all is well, return successful user return done(null, user); }); })); var isValidPassword = function(user, password){ return bCrypt.compareSync(password, user.password); } // Generates hash using bCrypt var createHash = function(password){ return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null); } }; 

路线:

 api.post("/signup", passport.authenticate("signup", { successRedirect: "/profile", failureRedirect: "/", failureFlash: true })) api.post("/login", passport.authenticate("login", { successRedirect: "/profile", failureRedirect: "/login"//, failureFlash: true })) router.get("/", function(req, res) { // serve index.html res.render("index", { title: 'Home', user: req.user, message: req.flash("message") }) }) 

它在login后直接访问的页面上工作,我控制如下:

 router.get("/profile", isLoggedIn, function(req, res) { res.render("profile", { title: 'Gebruikersprofiel van ' + req.user.firstname + " " + req.user.lastname, user: req.user // get the user out of session and pass to template }) }) function isLoggedIn(req, res, next) { console.log(req.session) // if user is authenticated in the session, carry on if (req.isAuthenticated()) return next() // if they aren't redirect them to the home page res.redirect("/login") } 

到目前为止,我已经尝试添加中间件来将req.user添加到req.session中,并在loginPOST中执行相同的操作。 另外我试过改变我在app.js中初始化中间件的顺序。 我正在使用新的快速会话版本,没有CookieParser,因为我读了CookieParser不再需要。

如果有人能以任何方式帮助我,将不胜感激! 我被卡住了一段时间(和其他人一样)。

       

网上收集的解决方案 "req.session.passport为空:req.user未定义"

问题不是我在设置会话或一般护照方面做错了什么,而是在我的链接中。 我在某个地方看到有人偶然在多个领域工作(他的平台显然是多服务器),这让我今天早上通过我的链接看。

显然,我用www连接到我的网站。 前缀,但会议初始化没有万维网的地方。 在URL前面。 我在cookies里看到了这个 因此,解决scheme是一致地链接到网站,要么有www。 前缀无处不在。