【问题标题】:what is passport.initialize()? (nodejs express)什么是passport.initialize()? (nodejs快递)
【发布时间】:2018-03-20 12:57:54
【问题描述】:

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

我正在阅读一些手册,其中说,

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

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

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

但我不知道passport.initialize()

【问题讨论】:

    标签: javascript node.js npm passport.js node-modules


    【解决方案1】:

    来自 Passportjs 文档:

    在基于 Connect 或 Express 的应用程序中,passport.initialize() 需要中间件来初始化 Passport。如果您的应用程序 使用持久登录会话,passport.session() 中间件必须 也可以使用。

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

    【讨论】:

      【解决方案2】:

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

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

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

      所以基本上passport.initialize() 初始化了认证模块。

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

      【讨论】:

        【解决方案3】:

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

        TL;DR

        通过会话,initialize() 设置函数以序列化/反序列化请求中的用户数据。

        如果您不使用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.
        ...
        

        【讨论】:

        • 您好,例如在使用 JWT 令牌时,您真的不需要使用 passport.initialize() 吗?
        • @FabianBosler passport.initialize() 是否与session 的使用有关,因此取决于您实现JWT 身份验证的方式。目前我不能告诉你更多。
        • 你的回答解决了我的好奇心,谢谢!
        猜你喜欢
        • 2017-10-10
        • 1970-01-01
        • 1970-01-01
        • 2021-04-22
        • 2022-01-15
        • 2018-01-07
        • 2012-07-04
        • 1970-01-01
        • 2015-04-11
        相关资源
        最近更新 更多