我现在正试图在我的应用程序中应用护照模块。
我正在阅读一些手册,并说,
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.initialize())
到底在做什么?
passport.session()
可能是护照使用会话信息,
但我不知道passport.initialize()
答案 0 :(得分:12)
passport.initialize()
是一个初始化Passport的中间件。
Middlewares是可以访问请求对象(req),响应对象(res)以及应用程序请求 - 响应周期中的下一个中间件函数的函数。
Passport是用于验证请求的Node的身份验证中间件。
所以基本上passport.initialize()
初始化认证模块。
passport.session()
是另一个中间件,可以改变请求对象并更改用户'当前会话ID(从客户端cookie)到真正的反序列化用户对象的值。 It is explained in detail here.
答案 1 :(得分:4)
来自Passportjs文档:
在基于Connect或Express的应用程序中,passport.initialize() 中间件需要初始化Passport。如果你的申请 使用持久登录会话,passport.session()中间件必须 也可以使用。
如果我们看一下source code,我们可以看到passport.initialize()中间件基本上将护照实例添加到传入请求中,以便可以继续进行身份验证策略。
如果有会话,它也会被添加到请求中。
答案 2 :(得分:0)
有时最好看一下代码:passport github on initialize()
TL; DR
对于会话,
initialize()
设置用于对请求中的用户数据进行序列化/反序列化的功能。如果您不使用
passport.initialize()
,则不需要使用sessions
。
/**
* 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.
...