当前位置: 首页 > 面试题库 >

HTTP动词的Mongoose / Express授权

董意蕴
2023-03-14
问题内容

我已经在mongoose和express上运行了一个node.js REST服务。我还使用merse设置路由。

我现在想要实现的是以下几种sceanrios:

Scenario I: e.g. blogpost
- GET -> no authentication required
- POST/PUT/DELETE -> authentication required

Scenario II: e.g. user
- GET -> authentication required
- POST/PUT/DELETE -> authentication required plus username of logged in user has to match

我已经看过了Everyauth和mongoose-auth,但是找不到任何可以给我这种控制的东西。


问题答案:

忘记了Everyauth。这个图书馆太夸张了,恕我直言。实际上,实现身份验证非常简单,请遵循以下架构:

  1. 用户通过usernamepassword到达服务器;
  2. 服务器获取usernamepassword在DB中检查是否有该用户password。如果没有用户,则返回错误;
  3. 我们有一个用户,现在使用Express的内置会话机制。调用req.session.regenerate和在回调中执行req.session.userID = user.id。Express会自动将cookie发送给用户;
  4. 创建一个中间件(必须 其他任何请求处理程序 之前启动 ),该中间件基本上在数据库中搜索req.session.userID。如果找到一个,则将其存储在中req;即req.user = user
  5. 在视图中,您只需检查是否req.user设置了变量。如果是,则我们已通过身份验证。大功告成!

广告1 +
2)为了确保身份验证的安全性,您应该使用一些加密技术(和/或HTTPS)。例如,密码应分为两部分保存在数据库中:salthashsalt是随机生成的(在注册时)和hash = hash_it(pwd, salt),其中hash_it是一些哈希算法(例如:MD5或SHA256)。

现在可以通过几个步骤进行客户端身份验证(仅当您可以使用JavaScript时):

  1. 服务器将随机发送new_salt到登录页面(或在JavaScript中生成一个,无需隐藏生成算法);
  2. 用户发送AJAX请求give me salt for user X,服务器以salt存储在DB中的响应(salt公共);
  3. 对响应进行哈希pwd处理salt,然后再对结果进行哈希处理new_salt,将其存储在变量中hpwd;
  4. 客户端发送usernamehpwdnew_salt给服务器;
  5. 服务器pwd从DB 获取for usernamepwd使用new_salt进行哈希处理并将结果与​​进行比较hpwd(注意:您不存储new_salt)。

这种方法非常好,因为每次登录(从外部角度来看)都是随机的数据流经net(即使usernameand password相同)。

这很重要,因为password泄漏很严重。并不是因为有人可以破坏您应用程序的帐户(除非您是银行,否则这是很小的损失-
但是您不会问这样的问题:D)。主要是因为人们倾向于对多个站点(包括银行帐户)使用相同的密码。



 类似资料:
  • Mongoose Node.js Express TypeScript application boilerplate with best practices for API development. The main purpose of this repository is to show a good end-to-end project setup and workflow for wri

  • Node Express Mongoose A boilerplate application for building web apps using express, mongoose and passport. Read the wiki to understand how the application is structured. Usage git clone https://githu

  • Vue-Admin-Express-Mongoose 基于Vue2.0(Vue-cli)+ElementUI+Express+Mongoose的全栈开发环境 前端页面部分基于vueAdmin项目,修复了其中的一些BUG。 OnlineDemo 效果 用法 安装依赖 npm install 开发环境 首先,启动Express服务(4501端口),提供API接口,请确保已经安装MongoDB npm

  • Nodejs Express Mongoose Demo This is a demo application illustrating various features used in everyday web development, with a fine touch of best practices. The demo app is a blog application where us

  • Express & mongoose REST API Boilerplate in ES6 with Code Coverage Sponsor You can support the project by checking out our sponsor page. It takes only one click: Overview This is a boilerplate applicat

  • Node boilerplate This is my node boilerplate starter kit. I will continue to update with the latest tech to help make make node servicessuper easy and efficient to kick start. Whats out the box? Frame