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:
- Once the client requests an HTML page with a form, the server generates two random tokens.
- 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.
- Each time a user submits the form, the client sends tokens back to the server.
- 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:
- Make sure that the application references the System.Web.WebPages.dll assembly.
Create a master page that generates an AntiForgery token:
<form id="form1" runat="server"> <%= System.Web.Helpers.AntiForgery.GetHtml() %> </form>
During master page initialization, add a handler for the
Page.PreLoad
event:In the event handler, call the Validate method to check whether the token is valid: