node.js - Passport.authenticate 导出 -> Passport.authenticate( 一些东西 ) (req, res, next)?

标签 node.js express authentication passport.js passport-jwt

我不明白为什么在 passport.authenticate 函数之后需要 (req, res, next)

将其与express一起使用,我遵循了教程,没有很好地解释这段文字

PS:一切正常,我只是不明白为什么需要这样做

const passport = require('passport')

module.exports = (req, res, next) => {
  passport.authenticate('jwt', (err, user) => {
    if (err || !user || user.isAdmin !== true) {
      res.status(403).send({
        message: 'Request blocked, only administrators'
      })
    } else {
      req.user = user
      next()
    }
  })(req, res, next)
}

作为中间件的函数调用

app.get('/admin', isAdmin, (req, res) => {
    res.send({
      message: 'You are an admin'
    })
  })

Passport 策略配置

passport.use(
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: config.jwtSecret
  }, async (jwtPayload, done) => {
    try {
      const user = await User.findOne({
        where: {
          id: jwtPayload.id
        }
      })
      if (!user) {
        return done(new Error(), false)
      }
      return done(null, user)
    } catch (err) {
      return done(new Error(), false)
    }
  })
)

PSS:我必须为用户身份验证创建另一个名为 isUser.js 的文件,如果我想将它们放在同一个文件中并要求它们像这样,我该怎么办

const Auth = require('./Auth')
Auth.isUser
Auth.isAdmin

我尝试过,但我不知道如何使用这种类型的函数来做到这一点:(

最佳答案

Express Route next() 在当前方法/中间件中处理完请求后,调用下一个路由处理程序或应该处理该请求的中间件。

因此,根据您的代码(查看代码中我的评论):

const passport = require('passport')

module.exports = (req, res, next) => {
  passport.authenticate('jwt', (err, user) => {
    if (err || !user || user.isAdmin !== true) {
      res.status(403).send({
        message: 'Request blocked, only administrators'
      })
    } else {
      req.user = user // THE user OBJECT IS ADDED TO THE req OBJECT SO THE NEXT ROUTE HANDLING METHOD/MIDDLEWARE MAY GET ACCESS TO THIS ADDED user OBJECT AND MAY USE IT
      next() // THIS CALL THE NEXT ROUTE METHOD/MIDDLEWARE
    }
  })(req, res, next)
}

因此,在此处执行 next() 后,请求将被传递给另一个名为 isAdmin 的中间件处理,该中间件将根据从上一个中间件添加的请求中检索到的添加的用户对象来检查当前用户是普通用户还是管理员用户,如 req.user = user

因此,如果您想避免为 isAdmin 创建单独的文件,那么您可能会这样:

const passport = require('passport')
// INCLUDE YOUR AUTH MIDDLEWARE FILE HERE
const isAdmin = require('./PATH/TO/isAdmin')

    module.exports = (req, res, next) => {
      passport.authenticate('jwt', (err, user) => {
        if (err || !user || user.isAdmin !== true) {
          res.status(403).send({
            message: 'Request blocked, only administrators'
          })
        } else {
          req.user = user
          // COMMENT OUT BELOW LINE
          // next()
          // IMPLEMENT THE AUTH LOGIC HERE, SOMETHING LIKE BELOW
          if (user.isAdmin()) {
          }
        }
      })(req, res, next)
    }

希望这对你有帮助

关于node.js - Passport.authenticate 导出 -> Passport.authenticate( 一些东西 ) (req, res, next)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56570335/

相关文章:

JAVA相当于验证登录信息?

python - Flask-principal 教程(auth + auth)

node.js - NodeJS 竞争条件?

node.js - 使用node/express/Multer,如何 "first"检查参数?

node.js - 图片上传: Node Multer 'LIMIT_UNEXPECTED_FILE' error

flutter - 多个设备(android、ios 和 web)使用相同的 google clientId 和 clientSecret

javascript - NodeJS - 所有短(缩写)词到全词功能模块

node.js - 为什么bulkCreate 只在DB 中写入有限数量的记录(Postgres && Sequelize)

node.js - 如何将不同模块中的一条路由与index.js 中的 "require it"分开?

node.js - 使用 cookie 的 Express 代理 API 调用