了解护照序列化反序列化

node.js Node.js

泡芙西里

2020-03-18

您如何向外行解释Passport的序列化和反序列化方法的工作流程。

  1. 叫到哪里user.idpassport.serializeUser了?

  2. 我们passport.deserializeUser紧接着在工作流程中调用它吗?

    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user.id); 
       // where is this user.id going? Are we supposed to access this anywhere?
    });
    
    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });
    

我仍在努力寻找解决方案。我有一个完整的工作应用程序,没有遇到任何类型的错误。

我只是想了解这里到底发生了什么?

任何帮助表示赞赏。

第2131篇《了解护照序列化反序列化》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Tom伽罗 2020.03.18

对于使用Koa和koa-passport的任何人

知道在serializeUser方法中设置的用户密钥(通常是该用户的唯一ID)将存储在:

this.session.passport.user

done(null, user)在deserializeUser中设置时,“ user”是数据库中的某些用户对象:

this.req.user 要么 this.passport.user

由于某种原因,this.user当您在deserializeUser方法中调用done(null,user)时,永远不会设置Koa上下文。

因此,您可以在调用app.use(passport.session())之后将自己的中间件放入this.user中,如下所示:

app.use(function * setUserInContext (next) {
  this.user = this.req.user
  yield next
})

如果您不清楚serializeUser和deserializeUser的工作方式,请在Twitter上打我。@yvanscher

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android