Understand Anti-forgery Token In ASP.NET MVC

AZHARUL | 05-Jul-2024 10:16:41 AM | Time to read: 2 Min

A Full ASP.NET Core MVC Tutorial is Coming Soon…………

 

 

In this article, we will try to understand Anti-forgery Token in ASP.NET MVC.

Anti-forgery stands for “Act of copying or imitating things like a signature on a check, an official document to deceive the authority source for financial gains”.

Now, in the case of web applications, it is termed as CSRF. CSRF is a method of attacking website where attackers imitate a trusted source sending the data to the site.

[Here attacker acts like a trusted source and sends data to site and website processes the data by trusting the request.]

Now, let’s take an example.

  • Now we have created a new MVCWebapplication project by File- New Project- WebApplication MVC.
  • Now add TransferAmt action method which will fetch the value of amount as amt and act as the account from Request.Form as shown below.
<html>
<head>
    <title>Transfer money</title>
</head>
<body>
    <div> Transfer
        <form action="Home/TransferAmt" method="post">
            Amount <input type="text" name="amount" value="" /><br />
            Account No. <input type="text" name="account" value="" /><br />
            @Html.AntiForgeryToken()
            <input type="submit" value="Add Money" />
        </form>
    </div>
</body>
</html>

Now you can see even we are able to access TransferAmt from another application, which is security breach.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SignIn(string Email,string Password)
{
    string sErrMsg="";

	try
    {
        if (ModelState.IsValid)
        {
            if (!IsValidCredentials(Email,Password))

Now to overcome this we will use Antiforgery Token with the help of @Html.AntiForgeryToken() in view and [ValidateAntiForgeryToken()] on actionmethod.

  • Now run the application and click on Play the ultimate game and you will get an error which is protecting your website from unwanted anti-forgery requests.

 

 

Follow us in YouTube and Stay Tuned………………