passport.initialize() 是什么? (节点表达)

what is passport.initialize()? (nodejs express)

我现在正尝试在我的应用程序中应用护照模块。

我正在阅读一些手册,那里说,

app.use(passport.initialize());
app.use(passport.session());

app.use(passport.initialize()) 到底在做什么?

passport.session()可能是passport要使用session信息,

但是我不知道 passport.initialize()

来自 Passportjs 文档:

In a Connect or Express-based application, passport.initialize() middleware is required to initialize Passport. If your application uses persistent login sessions, passport.session() middleware must also be used.

如果我们看一下 source code,我们可以看到 passport.initialize() 中间件基本上将护照实例添加到传入请求中,以便可以继续执行身份验证策略。
如果有会话,它也会添加到请求中。

passport.initialize()是初始化Passport的中间件。

Middlewares 是可以访问请求对象 (req)、响应对象 (res) 以及应用程序请求-响应周期中的下一个中间件函数的函数。

Passport 是 Node 的身份验证中间件,用于对请求进行身份验证。

所以基本上 passport.initialize() 初始化身份验证模块。

passport.session() 是另一个中间件,它改变请求对象并将当前作为会话 ID(来自客户端 cookie)的 'user' 值更改为真正的反序列化用户对象。 It is explained in detail here.

有时最好查看代码:passport github on initialize()

TL;DR

对于会话,initialize() 将函数设置为 serialize/deserialize 来自请求的用户数据。

如果您不使用sessions,则不需要使用passport.initialize()

/**
 * Passport initialization.
 *
 * Intializes Passport for incoming requests, allowing authentication strategies
 * to be applied.
 *
 * If sessions are being utilized, applications must set up Passport with
 * functions to serialize a user into and out of a session.  For example, a
 * common pattern is to serialize just the user ID into the session (due to the
 * fact that it is desirable to store the minimum amount of data in a session).
 * When a subsequent request arrives for the session, the full User object can
 * be loaded from the database by ID.
 *
 * Note that additional middleware is required to persist login state, so we
 * must use the `connect.session()` middleware _before_ `passport.initialize()`.
 *
 * If sessions are being used, this middleware must be in use by the
 * Connect/Express application for Passport to operate.  If the application is
 * entirely stateless (not using sessions), this middleware is not necessary,
 * but its use will not have any adverse impact.
...