Skip to main content
All docs
V24.1

Prevent Cross-Site Request Forgery (CSRF)

  • 2 minutes to read

In a Cross-Site Request Forgery (CSRF) attack, a threat actor tricks an authenticated user into executing unauthorized commands. These attacks are possible because web browsers automatically send certain authentication token types with each request.

Tip

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

To protect your application from CSRF attacks, you can use the synchronizer token pattern (STP) technique. This technique works as follows:

  1. Once the client sends a GET request, the server generates a token associated with the current user’s identity.
  2. In response to the request, the server returns HTML that contains this token in a hidden field.
  3. The client sends the hidden field with the token back to the server with each POST request.
  4. If the server receives a token that does not match the authenticated user’s identity, the server rejects the request.

To implement a synchronizer token pattern in your application:

  1. Create a master page that generates an AntiForgery token:

    <form id="form1" runat="server">
        <%= System.Web.Helpers.AntiForgery.GetHtml() %>
    </form>
    
  2. Handle the master page Pre_Load event:

    protected override void OnInit(EventArgs e) {
        base.OnInit(e);
        Page.PreLoad += OnPreLoad;
    }
    
  3. Call the Validate method to check whether the token is valid in the event handler:

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