Skip to main content
All docs
V24.2

Prevent Cross-Site Request Forgery Attacks (CSRF)

  • 2 minutes to read

In Cross-Site Request Forgery (CSRF) attacks, a threat actor tricks an authenticated user into executing unauthorized commands.

Tip

Refer to the following document to familiarize yourself with this vulnerability: ASP.NET Web Forms - Security Best Practices.

Use anti-forgery tokens to protect your application from CSRF attacks. These tokens work as follows:

  1. Once the client requests an HTML page with a form, the server generates two random tokens.
  2. The server adds these tokens in the response. It sends one token as an HttpOnly cookie and places another token in a hidden form field.
  3. Each time a user submits the form, the client sends tokens back to the server.
  4. If the server receives a request that does not include both tokens or if one of tokens was modified, the server rejects the request.

To use anti-forgery tokens in your application:

  1. Make sure that the application references the System.Web.WebPages.dll assembly.
  2. Create a master page that generates an AntiForgery token:

    <form id="form1" runat="server">
        <%= System.Web.Helpers.AntiForgery.GetHtml() %>
    </form>
    
  3. During master page initialization, add a handler for the Page.PreLoad event:

    protected override void OnInit(EventArgs e) {
        base.OnInit(e);
        Page.PreLoad += Page_PreLoad;
    }
    
  4. In the event handler, call the Validate method to check whether the token is valid:

    protected void Page_PreLoad(object sender, System.EventArgs e) {
        if (IsPostBack)
            System.Web.Helpers.AntiForgery.Validate();
    }