Home > Back-end >  ExpressJS: How to prevent a user from posting/patching code inside req.body
ExpressJS: How to prevent a user from posting/patching code inside req.body

Time:02-10

I'm developing an API with expressJS. This API is a semi-weblog service, and clients can create, update and delete their posts and contents. I have a sec urity concern about implementing its post and patch routes.

If the user injects some JS code and sends it to API to store in Mongodb, could these codes affect our API? How can I prevent users from posting and patching requests with any code inside them?

I have found "xss-clean" middleware to sanitize the user input body, is it enough for this purpose?

Because it is very important to me to ensure that I am using the correct middleware to protect this API, I am asking this question.

CodePudding user response:

If the user injects some JS code and sends it to API to store in Mongodb, could these codes affect our API?

Generally speaking: It won't.

The code come into express as a message body. It gets parsed by your middleware into a data structure where it will appear as a string. You then put that string in an object of structured data that you pass through the Mongodb client API which sends it to the database with any escaping that is needed.

I have found "xss-clean" middleware to sanitize the user input body, is it enough for this purpose?

XSS is an attack in which data injected into an HTML document contains special characters which are treated as special characters in HTML.

e.g.

<h1>{{ your_name }}</h1>

Where your_name is data that contains <script>...</script>.

This is generally dealt with by applying proper escaping to the data (at a very basic level that means replacing < with &lt;).

XSS won't affect your API directly.


If your data is going to be taken out of the Mongodb store and injected into an HTML document, then XSS is a consideration.

xss-clean is a wrapper around xss-filters.

xss-filters looks (I've only glanced at it) like a good module and is designed to be used as an output filter (i.e. run just before you insert data into an HTML document).

xss-clean works as an input filter, which isn't a good approach. It makes your data HTML safe at the expense of making it not useful for any purpose other than HTML. You might want to use the data in an email, or generate a report in Excel format.

  • Related