I'm practicing making websites and i was wondering what are some ways to prevent CSRF? It seems like kind of a tough one to fix.
thx in advance
Some people attempt to prevent it by checking the referer, but that's not a very good solution since referers can be spoofed and some browsers don't send referers at all.
The proper way to secure a site against CSRF is to include tokens on each request which modifies data. These tokens should be random and unpredictable, and they should be different for each session.
Here is an example workflow:
For improved security you can also make it so the token changes after each time it's used (like Valhalla does), however this can potentially lead to decreased usability (e.g. a user who opens multiple tabs and then tries to perform an action on each of them. The first will work but the others will be rejected). That issue can be overcome by adding more data to the session so that multiple tokens are saved, but this can make things more complicated and requires the server to keep track of more data.
Here is the CSRF-prevention framework I wrote for Valhalla in PHP: Link
Here's something that might be useful:
Owasp CSRF Prevention Cheat Sheet
OWASP does a pretty great job describing web vulnerabilities and how to prevent them. They also have their CSRF Guard framework for Java which works pretty well. It's a pain in the ass to implement though and the documentation isn't that great (but it never is for frameworks it seems).
Wow, thanks for the really helpful answers guys. And thanks for the quick responses. I have a lot to read up on now and practice.