3
votes

I read this tutorial which gives a nice explanation to prevent CSRF but it is still going out from my brain. According to this tutorial in method one they are including a random token with each request. So in the form they have included something like this:

<input type="hidden" name="<?php echo $token_id; ?>" value="<?php echo $token_value; ?>"

and after submitting the form they are checking for whether the token is matching or not.

How is it helping in preventing CSRF?
I am confused when the attacker sends a malicious link to a user, and when the user clicks on it then according to me the token will match everytime.

1
btw: Tokens are not the only way to prevent CSRF. It can be easier to use the origin header: wiki.mozilla.org/Security/Origin - Francois Bourgeois
@Francois Thanks for pointing this out..i will try to dive into it :) - Shubham Gupta
@brasofilo thanks for editing it..you made it more readable..i will keep these edit areas in my mind so that the next time when i will ask for help i dont commit these mistakes again :) - Shubham Gupta
@shubham, honored to hear that :) Pro tip: use a browser spell checker, this way you improve your English and post questions with less mistakes. Good luck! - brasofilo

1 Answers

6
votes

The token in the page has to match the token stored in a cookie (or session).

The site that set the cookie knows what that token value is and can specify it in the form.

A third party attacker's site cannot know what that token value is, so can't specify it.

You test to see if the token in the cookie matches the one in the form data, if they don't you reject the request as CSRF.