Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValidateAntiForgeryToken in WebForms Application

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?

like image 887
Dov Miller Avatar asked Sep 13 '18 13:09

Dov Miller


1 Answers

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.

like image 183
KYG Avatar answered Oct 03 '22 14:10

KYG