Click here to Skip to main content
15,883,982 members
Articles / Web Development / ASP.NET

What is CSRF Attack and How Can We Prevent the Same in MVC?

Rate me:
Please Sign up or sign in to vote.
4.60/5 (37 votes)
25 May 2015CPOL2 min read 79.1K   21   8
CSRF (Cross site request forgery) is a method of attacking a website where the attacker imitates a.k.a forges as a trusted source and sends data to the site.

CSRF stands for Cross site request forgery. So if you see the dictionary meaning of forgery:

“It’s an act of copying or imitating things like signature on a cheque, official documents to deceive the authority source for financial gains.”

So when it comes to website this forgery is termed as CSRF(Cross Site Request Forgery).

CSRF is a method of attacking a website where the attacker imitates a.k.a forges as a trusted source and sends data to the site. Genuine site processes the information innocently thinking that data is coming from a trusted source.

For example, consider the below screen of an online bank. End users use this screen to transfer money.

Image 1

Below is a forged site created by an attacker which looks a game site from outside, but internally it hits the bank site for money transfer.

Image 2

The internal HTML of the forged site has those hidden fields which have the account number and amount to do money transfer.

HTML
Win 1000000 US$ <form action="http://localhost:23936/Genuine/Transfer" 
method=post> <input type=hidden name="amount" value="10000" /> 
<input type=hidden name="account" value="3002" /> 
<input type=submit value="Play the ultimate game" /> 
</form>

Now let’s say the user has logged into the genuine bank site and the attacker sent this forged game link to his email. The end user thinking that it’s a game site clicks on the “Play the Ultimate Game” button and internally the malicious code does the money transfer process.

Image 3

So a proper solution to this issue can be solved by using tokens:

  • End user browses to the screen of the money transfer. Before the screen is served, server injects a secret token inside the HTML screen in form a hidden field.
  • Now henceforth when the end user sends request back, he has to always send the secret token. This token is validated on the server.

Image 4

Implementing token is a two-step process in MVC:

First apply “ValidateAntiForgeryToken” attribute on the action.

C#
[ValidateAntiForgeryToken]
public ActionResult Transfer()
{
            // password sending logic will be here
            return Content(Request.Form["amount"] + 
                " has been transferred to account " 
                + Request.Form["account"]);
}

Second in the HTML UI screen, call “@Html.AntiForgeryToken()” to generate the token.

HTML
Transfer money <form action="Transfer" method=post>
Enter Amount <input type="text" name="amount" value="" />
Enter Account number <input type="text" name="account" value="" />
@Html.AntiForgeryToken() <input type=submit value="transfer money" /> </form>

So now henceforth when any untrusted source sends a request to the server, it would give the below forgery error.

Image 5

If you do a view source of the HTML, you would find the below verification token hidden field with the secret key.

HTML
<input name="__RequestVerificationToken" type="hidden" 
value="7iUdhsDNpEwiZFTYrH5kp/q7jL0sZz+CSBh8mb2ebwvxMJ3eYmUZXp+uofko6eiPD0fmC7Q0o4SXeGgRpxFp0i+
Hx3fgVlVybgCYpyhFw5IRyYhNqi9KyH0se0hBPRu/9kYwEXXnVGB9ggdXCVPcIud/gUzjWVCvU1QxGA9dKPA=" />

For further reading do watch the below interview preparation videos and step by step video series.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
QuestionThanx Pin
Rockdeveloper1627-Mar-17 4:43
Rockdeveloper1627-Mar-17 4:43 
QuestionHow can we implement ValidateAntiForgeryToken to GET method in MVC Pin
sanjay2436573-May-16 20:02
sanjay2436573-May-16 20:02 
GeneralMy vote of 5 Pin
Raul Iloc11-Jun-15 20:57
Raul Iloc11-Jun-15 20:57 
QuestionI can't understand how it's secure to display token value in a hidden HTML field input Pin
InvisibleMedia28-May-15 13:09
professionalInvisibleMedia28-May-15 13:09 
Hi,
I don't understand what that token serves...what seems to be secure to show a token over the internet ?


But, what about headers into HTTP protocol ?...all "session key" for server-side identification resides in HTTP headers...session key are always transmitted in plain text (except with SSL)

suggestion : use session key instead
QuestionPartially effective Pin
jbrentonprivate26-May-15 7:33
jbrentonprivate26-May-15 7:33 
QuestionI have One Question Pin
Tridip Bhattacharjee26-May-15 5:13
professionalTridip Bhattacharjee26-May-15 5:13 
Generalgood article Pin
Rajesh Chavakula Rajesh25-May-15 20:31
Rajesh Chavakula Rajesh25-May-15 20:31 
GeneralMy vote of 5 Pin
hoangcute9x25-May-15 15:50
professionalhoangcute9x25-May-15 15:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.