问题
I've successfully created a websocket on my Django(v. 2.0)-powered website using Django channels (v. 2.1.5).
Everything is fine but I'm wondering what about CSRF token. Is it needed in case of websockets? Documentation says that it's enough to use OriginValidator
to prevent such thread but I'd like to ensure that. I mean, what has happend to CSRF token? Am I just sending data through secure channel without it and backend automagically checks everything? And if that's so then why? And why simple views can't do that?
I know it's preety open question but I was not able to find any specific explanation, if anyone has one I'd more than greatful.
Cheers!
回答1:
The CSRF token are not required when you are using websocket connections.
When you visit a malicious website, it could send a post-request via javascript to another website, where you are currently logged in. Your browser would also send you session-cookie to this other website, so the webserver thinks that you did willingly send this post-request and would execute the request. The CSRF-cookie prevents this. Thins the malicious site can not read the value of the CSRF-cookie, it can not add the value to the post-request.
It is also possible for a malicious website to open a websocket connection to a different site. That is the reason, why you have to use a OriginValidator. If you use it, then the server accepts only websocket connections from your site.
When the malicious site tries to open a connection to your server, it gets rejected right away.
So the difference between a post-request and a websocket-connections is, that browsers sent a origin header on websocket connections but not always on post requests.
It seems that modern browsers always send the origin header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
So maybe you don't have to use the CSRF-cookie at all. See also: CSRF protection with CORS Origin header vs. CSRF token
来源:https://stackoverflow.com/questions/53176767/cross-site-request-forgery-protection-with-django-and-websockets