Link Search Menu Expand Document

Mass Assignment in NodeJS

Using MongoDB

Vulnerable Example

This Express.js route allows for an application to be signed up to. The logic checks whether a user already exists with the specified username; otherwise, it creates the new user by passing the whole User object passed from the request to the insert function:'/signup', function (req, res) {
    const {username} = req.body;
    usersCollection.countDocuments({username}, function (err, count) {
        if (count === 0) {
            const newUser = req.body;
        } else {

Assuming an HTTP form is like this:

<form method="POST" action="/signup">
  <input name="username" />
  <input name="password" />

And assuming that the web application uses an is_admin field to implement a rudimentary access control mechanism, an attacker could craft a request adding the is_admin POST field with value 1.


MongoDB does not provide any specific facility to prevent Mass Assignment; it is up to the developer to create the object to be inserted by only using a subset of all the fields that might be present in the request:

const {username, password} = req.body;
usersCollection.insert({username, password});