Nodejs - Passport - 无法将用户序列化到会话中

Pho*_*rce 2 node.js passport.js

我正在使用以下库:

护照-oauth2-密码-授予

我正在尝试做的是以下内容:

  1. 对 API 进行身份验证(用户名/密码)
  2. 获取访问令牌
  3. 从 API 获取用户配置文件
  4. 使用护照登录用户

我正在使用以下实现:

PasswordGrantStrategy.prototype.userProfile = function(accessToken, done) {
    return done(null, { real_name: 'Foo Baz', email: 'test@test.com' });

}
passport.use(new PasswordGrantStrategy({
    tokenURL: 'http://api.local/oauth/token',
    clientID: "2",
    clientSecret: "",
    grantType: "password",
},
function(accessToken, refreshToken, profile, done) {
  return done(null, profile);
}));

function authenticate() {
    return function(req, res, next) {
        var username = "email@email.com";
        var password = "password";

        passport.authenticate('password-grant', {
            username: username,
            password: password
        })(req, res, next);
    };
}
Run Code Online (Sandbox Code Playgroud)

使用用户名/密码登录 API

它将配置文件传递给回调函数,passport.use(new PasswordGrantStrategy但是,我收到以下错误:

无法将用户序列化到会话中

它应该在我传递配置文件时进行序列化,并且一切看起来都很好。现在这是否意味着会话可能存在问题?

paq*_*ash 5

您需要向 Passport 提供 serializeUser 和 deserializeUser 方法才能使其工作。

来自官方文档:

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

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});
Run Code Online (Sandbox Code Playgroud)