I have the following situation:
Lets have a REST API with a POST endpoint, e.g.: POST /users
. Then I send the following request body to this endpoint:
{
"data": {
"firstname": "<script>alert('John')</script>",
"lastname": "<script>alert('Doe')</script>"
}
}
These data are then saved to the users SQL table, to the columns firstname and lastname.
Now I have a simple PHP web application (a classic, non-single page, server side rendered PHP web app), which has access to this users table too. Now when he pulls out the above inserted firstname and lastname and then renders them to a HTML view, the <script>
tags will be rendered too, the code between <script>
tags will run in the browser, so the alerts will be shown. Obviously, I don't want this, because it is an XSS vulnerability. The question is, what is the right way to avoid this vulnerability:
- Sanitize the POST request on the backend - so escape the
<script>
tags from the data before the data are saved to the DB
or
- Don't sanitize the POST request on the backend - so save the data with the
<script>
tags to the DB as they are. Then when the PHP webapp loads the data from the DB, he should escape the<script>
tags before he renders the data to the HTML view.
In my opinion, the second approach is the right approach, because XSS is an issue only for the frontends, however, the REST API endpoints can be called from non-frontend apps too, where the avoiding of the XSS vulnerability with escaping the <script>
tags is irrelevant. And maybe, some services will need to get the full HTML code from the backend and not only its escaped version. But what do you think?
Thank you so much!