【问题标题】:add basic auth to express rest api添加基本​​身份验证来表达rest api
【发布时间】:2022-01-20 14:57:33
【问题描述】:

所以我有rest api,我在mongoDB中存储用户数据,我想将基本身份验证添加到我的api但我卡住了,我想检查用户是否在某些路径上获得授权,例如在/update上,如果用户是 auth 执行请求,如果不发送该用户未授权

我存储用户的代码是 db

  const addUser = async (req, res) => {
  const checknick = await User.find({ nickname: req.body.nickname }) //checks if user exists with nickname
  if (checknick.length !== 0) {
    return res.send({
      message: 'user already exists, please use another nickname',
    })
  }

  const secretInfo = await hash(req.body.password).catch((err) =>
    res.send('password is required!')
  )
  const user = new User({
    name: req.body.name,
    surname: req.body.surname,
    nickname: req.body.nickname,
    password: secretInfo.password,
    salt: secretInfo.salt,
  })
  user.save((err, result) => {
    if (err) {
      return res.send(err)
    }
    res.send('user added sucesessfully')
  })
}

我在哪里验证用户

const verify = async (req, res) => {
  const user = await User.findOne({ nickname: req.body.nickname })
  if (!user) {
    return
  }

  const { password } = await hash(req.body.password, user.salt).catch((err) =>
    res.send('password is required')
  )

  const verifiedUser = await User.findOne({
    nickname: req.body.nickname,
    password: password,
  })

  if (!verifiedUser) {
    return false
  }
  return true
}

最后是登录逻辑

const login = async (req, res) => {
  const access = await verify(req, res)

  // console.log(req.headers)
  if (access) {
    res.send('logged in')
    console.log(req.headers)
    return
  }
  return res.status(401).send('failed to login')
}

一切正常,但我想使用授权标头发送用户和密码信息

【问题讨论】:

    标签: node.js mongodb rest express basic-authentication


    【解决方案1】:

    这是如何限制路由添加这个中间件功能之前 你想像这样限制的路线:

    app.post("/update", restrictTo("admin"));
    

    每个用户都必须有一个角色才能授权。这里我使用全局错误处理程序处理错误,但您可以通过其他方式处理错误:

    exports.restrictTo = (...roles) => {
        return (req, res, next) => {
            if (!roles.includes(req.user.role))
                return next(
                    new AppError('You dont have permission to do this action', 403)
                );
            next();
        };
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 2016-06-08
      • 1970-01-01
      • 2013-06-06
      • 2012-02-13
      • 1970-01-01
      相关资源
      最近更新 更多