【问题标题】:nodeJS code pattern => Express middleware/Oauth2/PassportnodeJS 代码模式 => Express 中间件/Oauth2/Passport
【发布时间】:2016-11-20 05:57:28
【问题描述】:

我继承了一个代码库,看起来他们在节点中运行中间件,具有以下 Oauth2 护照策略模式

module.exports = function (router) {
   router.get('/', function (req, res, next) {
       passport.authenticate('type', object, function(err, info) {

             //pass info object to next middleware

  })(req,res,next) <---where does this go?!?
})
}

从我目前对代码库的理解来看,这实际上是中间件链中最后一个函数调用,那我可以在最底层加一个中间件吗?

这听起来是正确的想法吗?

只是为了澄清我想要做什么:

  1. 通过中间件函数将数据从 Oauth 回调传递到请求中
  2. 执行数据库业务逻辑(创建或查找帐户)
  3. 使用智威汤逊登录
  4. 重定向

【问题讨论】:

    标签: node.js express oauth-2.0 passport.js jwt


    【解决方案1】:

    这似乎是使用护照authenticate 函数的“自定义回调”方法。如果您查看the documentation,您会看到他们希望如何使用它。也就是说,我不知道第二个参数应该做什么(object) - 它看起来像一个变量,但我没有看到它在任何地方定义,我不确定authenticate方法以这种方式接受参数。此外,自定义回调需要三个参数:erruserthen info... 这可能会让您感到困惑。

    好的,现在回到您的实际问题“我可以在底部添加一个中间件吗?”有点?事实是,此时您处于路由中间件中。如果匹配且身份验证成功,那么您应该为该路由执行所需的任何代码自定义回调中。这就是这种做事方式的意义所在。或者,您可以使用 passport.authenticate 作为中间件本身(它返回一个可用于 CommonJS 模式的中间件函数。

    如果您不想更改代码,那么您可以这样做:

    module.exports = function (router) {
      router.get('/', function (req, res, next) {
        passport.authenticate('PICK A VALID TYPE', function(err, user, info) {
    
           // this custom callback will be executed once auth completes
           // (either successfully or not
    
           // put code in here to perform DB business logic, login, and redirect
    
        })(req,res,next); <--- this executes the passport.authenticate middleware
      })
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 2014-02-17
      • 2015-03-24
      • 2016-11-15
      • 2019-08-13
      相关资源
      最近更新 更多