I have done some reading about the use of ValidateAntiForgeryToken
to prevent XSRF/CSRF attacks. However what I have seen seems to relate only to MVC.
These are the articles I've seen:
ValidateAntiForgeryToken purpose, explanation and example
CSRF and AntiForgeryToken
XSRF/CSRF Prevention in ASP.NET MVC and Web Pages
How can I implement this or something similar in a WebForms Application?
CSRF attacks are not exclusive to MVC application, webforms are vulnerable too.
Basically, CSRF attack exploits the trust that a site has in a user's browser, by requesting or posting information to the website, generally through hidden forms or JavaScript XMLHttpRequests within a the malicious website, as user using cookies stored in the browser.
To prevent this attacks you will need an antiforgery token, a unique token sent within your forms, that you need to validate before trusting the form's information.
You can find a detailed explanation here.
To protect your webforms apps against CSRF attacks (it's working in my projects), is to implement it in your master pages, like this:
Add new Class that will handle the CSRF Validations for you:
public class CsrfHandler
{
public static void Validate(Page page, HiddenField forgeryToken)
{
if (!page.IsPostBack)
{
Guid antiforgeryToken = Guid.NewGuid();
page.Session["AntiforgeryToken"] = antiforgeryToken;
forgeryToken.Value = antiforgeryToken.ToString();
}
else
{
Guid stored = (Guid)page.Session["AntiforgeryToken"];
Guid sent = new Guid(forgeryToken.Value);
if (sent != stored)
{
// you can throw an exception, in my case I'm just logging the user out
page.Session.Abandon();
page.Response.Redirect("~/Default.aspx");
}
}
}
}
Then implement this in your master pages:
MyMasterPage.Master.cs:
protected void Page_Load(object sender, EventArgs e)
{
CsrfHandler.Validate(this.Page, forgeryToken);
...
}
MyMaster.Master:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:HiddenField ID="forgeryToken" runat="server"/>
...
</form>
Hope you'll find this useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With