简体   繁体   中英

How to protect sensitive routes in express.js

so i'm building a node js application that runs express js and I set up a route like this, in app.js:

router.get("/db/:dbName", (req, res) => {
            var dbName = req.params.dbName
            if (dbName) {
                var coll = db.collection(dbName);
                coll.find().toArray()
                    .then(results => {
                        res.send(results);
                    })
                    .catch(err => {
                        console.error(err)
                    })
            } else {
                console.log("put a dbName")
            }

        })

What is does is that on the click of a button it reads from a mongodb database and outputs the documents in the "dbName" collection. I then had the idea to go to a seperate tab and type in "localhost:3000/db/collection" and of course it still works without the button (ie it returns all documents in the collection). My question is, what would be a way to prevent this behaviour, essentially only making the route accessible if you use the button.

You can use a middleware and look for a value which is passed by only clicking the button. If that values is not passed to the server you can check for it and accordingly take action


function middleware(req, res, next) {
 if(req.value) {
   next()  
 } else {
   return "Some error"
 }
}

app.route('/route', middleware, function(req, res) {})

For further check https://expressjs.com/en/guide/using-middleware.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM