NodeJS + Express: How to secure a URL

后端 未结 3 484
清歌不尽
清歌不尽 2021-01-29 23:48

I am using latest versions of NodeJS and ExpressJS (for MVC).

I usually configure my rest paths like this, for example:

app.get(\'/archive\', routes.arch         


        
相关标签:
3条回答
  • 2021-01-30 00:10

    A even simpler approach would be to add the following code in the App.js file.

    var auth = function(req, res, next) {
    
        if(isAdmin) {
    
            return next();
    
        } else {
    
            return res.status(400)
    
        }
    };
    
    app.use('/admin', auth, apiDecrement);
    

    As you can see the middleware is being attached to the route. Before ExpressJS goes forward, it executes the function that you passed as the second parameter.

    With this solution you can make different checks before displaying the site to the end user.

    Best.

    0 讨论(0)
  • 2021-01-30 00:21

    Yep, middleware is exactly what you want. A middleware function is just a function that works just like any other Express route handler, expept it gets run before your actual route handler. You could, for example, do something like this:

    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
    });
    

    You could specify requireLogin as a middleware to each of the routes you want to be protected, instead of using the app.all call with /admin/*, but doing it the way I show here ensures that you can't accidentally forget to add it to any page that starts with /admin.

    0 讨论(0)
  • 2021-01-30 00:32

    Like brandon, but you can also go the connect route

    app.use('/admin', requireLogin)
    app.use(app.router)
    
    app.get('/admin/posts', /* middleware */)
    
    0 讨论(0)
提交回复
热议问题