简体   繁体   中英

How to protect the frontend from XSS, caused by data from a REST API?

I have the following situation:

Lets have a REST API with a POST endpoint, eg: 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:

  1. Sanitize the POST request on the backend - so escape the <script> tags from the data before the data are saved to the DB

or

  1. 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!

You are right, generally you will want to:

  1. Validate incoming data before storing (for example, is this a real email address?)
  2. Escape right before output

Escaping should always happen right before, because you don't know during your INSERT statement how it should be escaped. Maybe your data only appears in HTML, but perhaps later on you will also want the same data to appear in a.csv export. JSON file, HTTP header, URL. Each format will have their own rules for escaping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM