Prevent MVC ASP.NET web application from Cross Site Forgery Attack
3 Tech Solutions · Post Prevent MVC ASP.NET web application from Cross Site Forgery
Attack Posting as Amol Wabale Publish Save Preview Close ComposeHTML Link
View Code
Program Flow
On application start index action is called which will return the view which contains form along with antiforgery token.
Thus the web server while serving this request will also send Antiforgery token or cookie, which will be used for validation later
On form submit button click the data will be posted back to server along with AntiForgeryToken, as AntiForgeryToken attribute is
written on controller action, the token will be validated
If the AntiForgery Token is valid than the request will be served or it will give error shown in above image.
Test
Load the start page of web application by starting application in browser.
Now we know that the save url will be something like http://localhost:62931/Home/SaveData
The submit button on the view will be pointing towards the above url, on clicking submit button the request will be served because posted data will have antiforgery details
On other hand if you copy and paste the above URL in other tab or other browser, it will give antiforgery error, The request will not be served, because it doesnt has the AntiForgeryToken
- All web applications are vulnerable to cross site forgery attack, the best way to prevent CSFR attack in MVC ASP.NET application is to use AntiForgeryToken
- The key role of Antiforgery tokeen is is during Post data request to verify source of data.
- When implementing web application using anti forgery token concept, for each page request web server sends a cookie to client side in browser.
- Thus when the client posts data this cookie or token will be used for validation to know if the post request is comming from a valid source.
- If the request is not from a valid source the cookie or token will be null or some random data, thus this request will not be served.
- If the AntiforgeryToken is invalid the server will return error : The required anti-forgery form field "__RequestVerificationToken" is not present.
- Refer image below
- The CSFR attack can be prevented by using [ValidateAntiForgeryToken] attribute before the specific controller actions, and @Html.AntiForgeryToken() HTML razor element in the form to be posted
- Refer below code : Controller actions
namespace CSFR.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View("Home");
}
[ValidateAntiForgeryToken]
public ActionResult SaveData()
{
return View("Home");
}
}
}
@{
ViewBag.Title = "Home";
}
<h2>CSFR Prevention Tutorial</h2>
<hr />
@using (Html.BeginForm("SaveData", "Home"))
{
@Html.AntiForgeryToken()
//Your other form inputs
//..
//..
//..
//..
<input type="submit" value="Delete My Account" />
}
No comments