Xét đoạn code sau:
import { encryptPassword } from "./util/passwords"
app.post("/signup", function (req, res) {
db.users.find(
{
username: req.body.username,
},
async (err, result) => {
// username, password, email, isAdmin
if (err) {
return res.status(500).json({ msg: "Error" })
} else if (result.length === 0) {
// insert user
await db.users.insert(req.body)
return res.status(200)
} else {
return res.status(409)
}
},
)
})Có thể thấy, nếu nó không tìm thấy user thì sẽ tạo usert mới dựa trên request body. Tuy nhiên, user có thể thêm vào request body một field nào đó chẳng hạn như isAdmin để có thể leo quyền. Đây được gọi là mass assignment.
Cách phòng chống là chỉ tạo record dựa trên một số field của request body thay vì sử dụng toàn bộ field.
Tip
Mass assignment thường xảy ra trong các ứng dụng cho phép người dùng chỉnh sửa profile của họ.