2

I am working on my first full stack application, specifically with the MERN stack, and have run into a bit of an issue. I am trying to implement a leaderboard stored in a db for a unity game on my website. I have everything working wherein the client can post and get scores from my MongoDB Atlas database using my Express api. However, in the case of a leaderboard, I need to insure that the scores can ONLY be sent by the client based on how the game goes. With the current working configuration, anyone can send spoof scores via the api without having to play the game.

I first thought was to try to implement JWT to authenticate that the api call was coming from the site, but in my head any auth token like JWT could still be copied down by a user and sent with spoofed scores easily with Postman.

I am not extensively familiar with databases and suspect that this could possibly be solved if I wasn't using a DBaaS provider like Atlas but I am not entire sure.

Any thoughts or recommendations would be greatly appreciated!

Kribs
  • 49
  • 6
  • This falls under the scope of csrf protection. Here is a good answer on the topic: https://security.stackexchange.com/a/203910. Approach 2 involves checking req.origin as mentioned in a comment below. – Jordan Wright Mar 02 '22 at 08:56

2 Answers2

3

You could define a middleware function and check the method of the incoming request:

const allowOnlyPost = (req, res, next) => {
    if (req.method !== 'POST') {
        return res.status(401).send(`Method ${req.method} not allowed`)
    }
    next()
}

module.exports = { allowOnlyPost }

And then apply it to the routes you want to protect:

const { allowOnlyPost } = require('./your/middleware/folder')

app.use('/route/to/protect', allowOnlyPost, (req, res) => { ... })
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29
  • 1
    Its not that i only want to allow post, i only want to allow posts coming from my website/client on that server. I essentially want to disallow posts coming externally – Kribs Mar 02 '22 at 08:26
  • 2
    You can control the `req` object for the `origin` of the request and filter on that. Check this post for more https://stackoverflow.com/a/18498769 – lpizzinidev Mar 02 '22 at 08:29
  • thank you so much i think you just saved my life haha, i very much appreciate the help – Kribs Mar 02 '22 at 08:41
1

An improvement to current answer's function could be:

const allowMethods = (...methods) => { 
    return (req, res, next) => {
        if (!methods.map(m => m.toUpperCase()).includes(req.method.toUpperCase())) {
            return res.status(401).send(`Method ${req.method} not allowed`)
        }
        next()
    }
}
module.exports = { allowMethods }

So you could use it like this:

const { allowMethods } = require('./your/middleware/folder')

app.use('/route/to/protect', allowMethods('get','post'), (req, res) => { ... })
damian
  • 104
  • 6