Updated on Kisan Patel
To avoid cross site scripting attack where a request to submitted to the form that is not originally the form where the request should be submitted, we can use @Html.AntiForgeryToken()
in the form.
@using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <div class="editor-label"> @Html.LabelFor(model => model.EmailID) </div> <div class="editor-field"> @Html.EditorFor(model => model.EmailID) @Html.ValidationMessageFor(model => model.EmailID) </div> }
@Html.AntiForgeryToken
line generated Hidded element in in the form with encrypted value and it is validated in the server side to ensure that CSRF is not happening
Just keeping the @Html.AntiForgeryToken()
in the form is not enough in the view. We also need to add [ValidateAntiForgeryToken]
attribute in the action method of the controller where the form is being submitted.
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Index(Details model) { }
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.