Avoiding cross-site request forgery (CSRF) with WebSockets
By using sessions, we are exposing users to a CSRF attack unless we put appropriate measures in place.
CSRF attacks
CSRF attacks are malicious attacks on a website in which unauthorized commands are sent from one user to a second site with hidden forms, AJAX requests, or any other method in a hidden way.
You can find a reference here: https://en.wikipedia.org/wiki/Cross-site_request_forgery.
Channels provides a tool that will help us to avoid this type of attack in a simple way:
- We define the allowed Hosts in
project_template/settings.py
. In our case, we are using environment variables inside Docker:ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS"). split(",")
- We edit
project_template/asgi.py
, by importingOriginValidator
. We must pass two parameters:URLRouter
(or any intermediary middleware) and theHosts
we want to protect:# project_template/asgi.py import django os.environ.setdefault...