I'm currently working on an app using Django 2.2 with djangorestframework 3.9.2. I am aware that Django itself provides protection against SQL Injection or in in the context of displaying content in django templates (XSS), but I've noticed that while I use Django REST API, all the CharFields in my models are not sanitized automatically.
Note: this question does not apply to django templates.
E.g. having a direct messages model (message/models.py
):
class Message(models.Model):
sender = models.ForeignKey(...)
receiver = models.ForeignKey(...)
message = models.CharField(max_length=1200)
timestamp = models.DateTimeField(...)
is_read = models.BooleanField(default=False)
Actually does not prevent anyone from sending a message with content <script>alert("Hello there");</script>
. It will be saved in database and returned by the REST API as is, allowing to remotely run any JS script (basically a Cross Site Scripting).
Is this an expected behavior? How can this be prevented?
You can use escape()
method inside serializer's validation:
from django.utils.html import escape
class MySerializer:
def validate_myfield(self, value):
return escape(value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With