DEV Community

Cover image for What is Cross-site request forgery (CSRF) in ASP.NET Web applications? - iFour
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

What is Cross-site request forgery (CSRF) in ASP.NET Web applications? - iFour

CSRF stands for Cross-site request forgery. CSRF is also known as the one-click attack which is used for Security purpose. It is an act of copying or imitating things like a signature on a cheque, official documents to deceive the authority source for financial gains. Cross-site request forgery is a web security Weak that allows an attacker to induce users to perform actions that they do not intend to perform.

Cross-site request foreign is generally described in relation to cookie-based session handling, it also arises in other contexts where the application automatically adds some user credentials to requests, such as HTTP, HTTPS, FTP Basic authentication, and certificate-based authentication.

To preclude Cross-site Request Foreign attacks, use anti-forgery tokens with any authentication protocol where the browser silently sends credentials after the user logs in. This includes cookie-based authentication protocols, such as forms authentication method authentication, as well as protocols such as Basic and Digest authentication

First of all, we discuss how Spring Security can protect applications from CSRF attacks, we'll explain what a CSRF attack is. Let's take a glance at a concrete example to urge a far better understanding.

Assume that your bank's website provides a form that permits transferring money from the currently logged in user to a different checking account. For instance, the HTTP request might look like:


POST /transfer HTTP/1.1
Host: bank.example.com
Cookie: JSESSIONID=randomid; Domain=bank.example.com; 
Secure; HttpOnly
Content-Type: application/x-www-form-urlencoded
amount=100.00&routingNumber=1234&account=9876

Enter fullscreen mode Exit fullscreen mode

You can pretend your authentication to your bank's website then if without logging out, visit an evil website. The evil website contains an HTML page with the subsequent form that looked like this.


<xmp><form action="https://web.archive.org/web/20210117060537/https://bank.example.com/transfer" method="post">
<input name="amount" type="hidden" value="100.00" />
<input name="routingNumber" type="hidden" value="evilsRoutingNumber" />
<input name="account" type="hidden" value="evilsAccountNumber" />
<input type="submit" value="Win Money!" /> </form>
</xmp>

Enter fullscreen mode Exit fullscreen mode

You like to win money, then you click on the submit button. within the process, you've got unintentionally transferred $100 to a malicious user. It’s just a fraud.

This whole process could be automated using JavaScript. This suggests you didn't even get to click on the button. Then how can we protect ourselves from such attacks?

Read More: How To Perform Repository Pattern In Asp.net MVC?

CSRF Workflow

Attacker sends a forgery request by publishing a web page, blog, email, etc.

Victim user login to a web server for his work and click on the forgery link unknowingly and send the request to the server.>

Request is validated at the server as a normal request and attacker resolves his purpose.

How to protect Cross-Site Request Forgery attacks?

An attacker can launch a Cross-Site Request Forgery Attacks when he knows which parameters and value combination are being used in a form. There is a list of methods you can use to block cross-site request forgery attacks.

For Testing Code in ASP.Net Core, first, we will create a new project. For creating a new ASP.Net C# Application it will open Visual Studio 2019. After that, you will select the menu option File -> New -> select New Project Click on Ok.

Image description

First of all, the new project creation window pops up, we will select the ASP.Net Web Application C# Application and then select the MVC Checkbox then click on the Next button. You will get the below display.

Image description

After selecting the framework and new model in the model folder and write below code.


using System;
using System.Collections.Generic;
using System.ComponentM.DataAnnotations;
using System.Linq;
using System.Web;

namespace Demo_crsf_blog.Ms
{ 
public class CollageInfo
{
  [Key]
  public int CollageID
  {
  get;
  set;
  }
  [Required (ErrorMessage = " please Enter Name")]
  public string CollageName
  {
  get;
  set;
  }
  [Required (ErrorMessage = "pleaes Enter Address")]
  public string CollageAddress
  {
  get;
  set;
  }

  [Required (ErrorMessage = "please Enter Department")]
  public string CollageDepartment
  {
  get;
  set;
  }
}
}

Enter fullscreen mode Exit fullscreen mode

Now Add New Controller for writing to the login of creating method.


using Demo_crsf_blog.Ms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Demo_crsf_blog.Controllers
{
  public class collageInfoController : Controller
  {
    [HttpGet]
    public ActionResult collageInfo()
    {
      return View();
    }
    [HttpPost]
    public ActionResult collageInfo(CollageInfo _clgInfo)
    {
      return View(_clgInfo);
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Searching for Dedicated ASP.NET Web Developer? Your Search ends here.

And last, add the view of the collagen method right-click on the collageInfo method and add a new view after that you will get the view of the create page.


                  <xmp>

@m Demo_crsf_blog.Ms.CollageInfo

@{
  ViewBag.Title = &quot;collageInfo&quot;;
}<h2>collageInfo</h2>


@using (Html.BeginForm()) 
{
  @Html.AntiForgeryToken()
<div class="form-horizontal"><h4>CollageInfo</h4>
<hr />
    @Html.ValidationSummary(true, &quot;&quot;, new { @class = &quot;text-danger&quot; })<div class="form-group">
      @html.LabelFor(m => m.CollageName, htmlAttributes: new { @class = &quot;control-label col-md-2&quot; })<div class="col-md-9">
        @html.EditorFor(m => m.CollageName, new { htmlAttributes = new { @class = &quot;form-control&quot; } })
        @html.ValidationMessageFor(m => m.CollageName, &quot;&quot;, new { @class = &quot;text-danger&quot; })</div></div>
<div class="form-group">
      @html.LabelFor(m => m.CollageAddress, htmlAttributes: new { @class = &quot;control-label col-md-3&quot; })<div class="col-md-9">
        @html.EditorFor(m => m.CollageAddress, new { htmlAttributes = new { @class = &quot;form-control&quot; } })
        @html.ValidationMessageFor(m => m.CollageAddress, &quot;&quot;, new { @class = &quot;text-danger&quot; })</div></div>
<div class="form-group">
      @html.LabelFor(m => m.CollageDepartment, htmlAttributes: new { @class = &quot;control-label col-sm-4&quot; })<div class="col-md-10">
        @html.EditorFor(m => m.CollageDepartment, new { htmlAttributes = new { @class = &quot;form-control&quot; } })
        @html.ValidationMessageFor(m => m.CollageDepartment, &quot;&quot;, new { @class = &quot;text-danger&quot; })</div></div>
<div class="form-group"><div class="col-md-offset-3 col-md-9">
        <input class="btn btn-default" type="submit" value="Create" /></div></div></div>
}
<div>
  @Html.ActionLink(&quot;Back to List&quot;, &quot;Index&quot;)</div>

@section Scripts {
  @Scripts.Render(&quot;~/bundles/jqueryval&quot;)
}
</xmp>

Enter fullscreen mode Exit fullscreen mode

After Adding Index view Just click on the run symbol this program will run without any bug or error and you will get the below output of this program.

Image description

Right-click on view and go to the source and copy code and save as .html run this page fill all field and click on create button your control is going to the view in AnitforegeryToken method and error was occurred. This protection is called the Cross-site request foreign.

Image description

Conclusion

This blog is helpful for understanding the concept of Cross-site request forgery. This is used the provide security on the website. All web application platforms are potentially vulnerable to CSRF. We have also discussed about all factors of CSRF including the main purpose of providing the strongly security.

Top comments (0)