Cross-Site Request Forgery (CSRF) attack is an attack where a malicious website sends a request to a web application/site that a user is already authenticated on.
In another words cross site request forgery (CSRF) attack is a type of attack where a request is submitted to the form that is not originally the form where the request should be submitted from. To prevent this kinf of attack, we can use @Html.AntiForgeryToken()
helper method in the ASP.NET MVC form and ValidateAntiForgeryToken
in the controller action attribute.
VIEW CODE
@using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <div class="editor-label"> @Html.LabelFor(model => model.FirstName) </div> <div class="editor-field"> @Html.EditorFor(model => model.FirstName) @Html.ValidationMessageFor(model => model.FirstName) </div> }
Notice the @Html.AntiForgeryToken
line in the above form. Because of that line, a hidden element is generated in the form with encrypted value that is validated in the server side to ensure that CSRF attack is not happening.
<form action="/PersonalDetail/Create" method="post"><input name="__RequestVerificationToken" type="hidden" value="lgp_fxdlYmHf7q4Tpn75nq1Pdd3m4G3Vnb1uFEJ0FBhYHdXyH4VFg8dxvO2ScYt_49ZQg7prob9RfNrj7IWHkOgcQjBEM2oX_W1VnHfAOSA1" /><div class="validation-summary-errors"><ul><li style="display:none"> ………….. </form>
Just keeping the @Html.AntiForgeryToken()
in the form is not enough. We also need to add ValidateAntiForgeryToken
attribute in the action method of the controller where the form is being submitted.
CONTROLLER ACTION CODE
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PersonalDetail personaldetail)
{
}
Now, we can be 100% sure that the request coming to this action method is 100% originating from our own form and there is no CSRF.
Views: 17164 | Post Order: 84