NodeJS + Express:如何保护URL

Fab*_* B. 22 authentication middleware login node.js express

我正在使用最新版本的NodeJS和ExpressJS(用于MVC).

我通常像这样配置我的休息路径,例如:

app.get('/archive', routes.archive);  
Run Code Online (Sandbox Code Playgroud)

现在我想要保护我的一/admin/*组URL,我的意思是我只需要简单的身份验证,它只是一个草稿.

例如,当用户尝试访问时,/admin/posts在向他发送相应的视图和数据之前,我会检查req.session.authenticated.如果没有定义,我会重定向到登录页面.

登录页面有一个简单的验证表单和一个登录控制器方法:如果用户确实发送了"正确的用户"和"正确的密码",我设置会话变量并对其进行身份验证.

我发现很难或者我不明白的是,在每次/ admin/*路径调用之前,如何实际制作"过滤"代码,我的意思是认证检查.

这与"中间件"快递功能有关吗?

谢谢

Mic*_*ley 70

是的,中间件正是你想要的.中间件函数只是一个与任何其他Express路由处理程序一样工作的函数,它会在您的实际路由处理程序之前运行.例如,您可以执行以下操作:

function requireLogin(req, res, next) {
  if (req.session.loggedIn) {
    next(); // allow the next route to run
  } else {
    // require the user to log in
    res.redirect("/login"); // or render a form, etc.
  }
}

// Automatically apply the `requireLogin` middleware to all
// routes starting with `/admin`
app.all("/admin/*", requireLogin, function(req, res, next) {
  next(); // if the middleware allowed us to get here,
          // just move on to the next route handler
});

app.get("/admin/posts", function(req, res) {
  // if we got here, the `app.all` call above has already
  // ensured that the user is logged in
});
Run Code Online (Sandbox Code Playgroud)

您可以指定要保护的每个路由requireLogin的中间件,而不是使用调用,但是按照我在此处显示的方式执行此操作可确保您不会意外忘记将其添加到任何以此开头的页面.app.all/admin/*/admin

  • 哇.... 所以 StackOverflow 确实有效,有时!:D ehehe 谢谢,这正是我所期望的那种答案。如果一切正常,我将在下午尝试并接受您的出色回答。再次感谢 (2认同)

Dav*_*tti 5

更简单的方法是在 App.js 文件中添加以下代码。

var auth = function(req, res, next) {

    if(isAdmin) {

        return next();

    } else {

        return res.status(400)

    }
};

app.use('/admin', auth, apiDecrement);
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,中间件已附加到路由上。在 ExpressJS 继续之前,它会执行您作为第二个参数传递的函数。

使用此解决方案,您可以在向最终用户显示站点之前进行不同的检查。

最好的。