node.js Passport.js - 错误:无法将用户序列化到会话中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19948816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:16:27  来源:igfitidea点击:

Passport.js - Error: failed to serialize user into session

node.jsexpressloginpassport.jspassport-local

提问by user2244925

I got a problem with the Passport.js module and Express.js.

我遇到了 Passport.js 模块和 Express.js 的问题。

This is my code and I just want to use a hardcoded login for the first try.

这是我的代码,我只想在第一次尝试时使用硬编码登录。

I always get the message:

我总是收到消息:

I searched a lot and found some posts in stackoverflow but I didnt get the failure.

我搜索了很多并在stackoverflow中找到了一些帖子,但没有失败。

Error: failed to serialize user into session
    at pass (c:\Development\private\aortmann\bootstrap_blog\node_modules\passport\lib\passport\index.js:275:19)

My code looks like this.

我的代码看起来像这样。

'use strict';

var express = require('express');
var path = require('path');
var fs = require('fs');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var nodemailer = require('nodemailer');

var app = express();

module.exports = function setupBlog(mailTransport, database){
var config = JSON.parse(fs.readFileSync('./blog.config'));

app.set('view options', {layout: false});

app.use(express.static(path.join(__dirname, '../', 'resources', 'html')));


app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'secret' }));
app.use(passport.initialize());
app.use(passport.session());


app.get('/blog/:blogTitle', function(req, res) {
  var blogTitle = req.params.blogTitle;
  if(blogTitle === 'newest'){
    database.getLatestBlogPost(function(post) {
      res.send(post);
    });
  } else {
    database.getBlogPostByTitle(blogTitle, function(blogPost) {
      res.send(blogPost);
    });
  }
});

passport.use(new LocalStrategy(function(username, password, done) {
  // database.login(username, password, done);
  if (username === 'admin' && password === 'admin') {
    console.log('in');
    done(null, { username: username });
  } else {
    done(null, false);
  }
}));

app.post('/login', passport.authenticate('local', {
  successRedirect: '/accessed',
  failureRedirect: '/access'
}));





app.listen(8080);
console.log('Blog is running on port 8080');

}();

Thanks.

谢谢。

回答by robertklep

It looks like you didn't implement passport.serializeUserand passport.deserializeUser. Try adding this:

看起来你没有实现passport.serializeUserpassport.deserializeUser。尝试添加这个:

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

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

回答by Kevin

If you decide not to use sessions, you could set the session to false

如果您决定不使用会话,则可以将会话设置为 false

app.post('/login', passport.authenticate('local', {
  successRedirect: '/accessed',
  failureRedirect: '/access',
  session: false
}));

回答by electblake

Sounds like you missed a part of the passportjs setup, specifically these two methods:

听起来你错过了passportjs设置的一部分,特别是这两种方法:

passport.serializeUser(function(user, done) {
    done(null, user._id);
    // if you use Model.id as your idAttribute maybe you'd want
    // done(null, user.id);
});

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

I added the bit about ._idvs. .idbut this snippet is from the Configure Sectionof docs, give that another read and good luck :)

我添加了一些关于._idvs..id但这个片段来自文档的配置部分,再读一遍,祝你好运:)

回答by Ganku Caelestis

Here an working but still lazy way to use sessions and still "serialisize" the values.

这是一种使用会话并仍然“序列化”值的有效但仍然懒惰的方法。

var user_cache = {};

passport.serializeUser(function(user, next) {
  let id = user._id;
  user_cache[id] = user;
  next(null, id);
});

passport.deserializeUser(function(id, next) {
  next(null, user_cache[id]);
});

in case or weird errors just ask yourself: "Do I rlly set '_id' in my user object?" - in most cases you dont. So use a proper attribute as key.

以防万一或出现奇怪的错误,只需问问自己:“我是否在我的用户对象中设置了‘_id’?” - 在大多数情况下你没有。所以使用适当的属性作为键。

回答by Isak La Fleur

Using Promise with serializeUser & deserializeUser:

将 Promise 与 serializeUser 和 deserializeUser 一起使用:

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

passport.deserializeUser((id, done) => {
  // console.log(`id: ${id}`);
  User.findById(id)
    .then((user) => {
      done(null, user);
    })
    .catch((error) => {
      console.log(`Error: ${error}`);
    });
});

Please see my github repofor a full code example how to solve this issue.

有关如何解决此问题的完整代码示例,请参阅我的github 存储库

回答by annguyen

in passport.use('local-login'...)/ or /('local-singup'...)

在passport.use('local-login'...)/ 或/('local-singup'...)

if err you have to return "false" err {return done(null, req.flash('megsign', 'Username already exists #!#'));} true {return done(null, false, req.flash('megsign', 'Username already exists #!#'));}

如果错误,你必须返回“false”错误 {return done(null, req.flash('megsign', 'Username already exists #!#'));} true {return done(null, false, req.flash(' megsign', '用户名已经存在#!#'));}