Is websockets
vulnerable to CSRF attacks, and how can one do this if Websocket
does authentication like login ?

- 66,732
- 177
- 439
- 641
2 Answers
I think YES.
If somehow the attacker initialized a socket connection from the client-side and sends message then yes, the CSRF attack is possible.
Of course, this is TRUE ONLY IF YOU ARE USING COOKIE BASED AUTHENTICATION.
As CSRF attacks use cookies, which are automatically sent by browser with the request, and the request gets authenticated.
If you are using cookies to authenticate the request and connection, then yes CSRF attack is possible.
To avoid these attacks, it is better to use TOKEN BASED Authentication like JWT.
No Cookie-based authentication == No need for CSRF protection.
here are a few helpful links regarding AUTHENTICATION:

- 2,048
- 1
- 17
- 21
-
I find this problematic. We are saying that token based authentication is better than cookie based authentication, but the first article you link talks about storing the JWT in localStorage. Why is that better? You've mitigated CSRF but you introduced XSS. I think "defense-in-depth" is a better answer than saying one method is "better" than another. – Daniel Bank Oct 20 '19 at 19:45
-
Most of the modern framework comes with input-sanitization which prevents XSS attacks themselves. But yes, we should be aware of such attacks. – niranjan_harpale Oct 21 '19 at 06:35
-
I agree with you --- ' "defense-in-depth" is a better answer than saying one method is "better" than another.' We must choose that approach which is best for our implementation and needs. – niranjan_harpale Oct 21 '19 at 06:40
-
where to store JWT token? we must store it in persistent storage and send it through authorization header, even if the attacker gets hold of it, he can't read data stored into it. – niranjan_harpale Oct 21 '19 at 06:58
-
Here is a good article on the subject... don't be put off by the subject, it is not a hit job on JWT's: http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/ – Daniel Bank Oct 22 '19 at 02:51
I hope this isn't too late being a year old, but you can check the Origin header in addition to HttpOnly session cookies. Ref: https://security.stackexchange.com/questions/76816/preventing-csrf-attacks-against-websocket-communications
Answer is also influenced by: https://channels.readthedocs.io/en/latest/topics/security.html
Token based authentication imo should be reserved for mobile applications.

- 807
- 3
- 15