Register Now

Forget Password

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

If you are not using ASP.NET MVC and how to implement CSRF protection in a regular ASP.NET web appli

If you are not using ASP.NET MVC and want to implement CSRF protection in a regular ASP.NET web application (Web Forms), you can use the `__RequestVerificationToken` provided by ASP.NET.

Here's an example of how to use anti-forgery tokens in a standard ASP.NET web application:

1. Open your web form (.aspx) and add the following code to create a simple form:

```html
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>CSRF Protection Demo</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="lblMessage" runat="server" EnableViewState="false"></asp:Label>
            <br />
            <asp:Button ID="btnSubmit" runat="server" Text="Submit Form" OnClick="btnSubmit_Click" />
        </div>
    </form>
</body>
</html>

 

Open the code-behind file (Default.aspx.cs) and add the following code:

 

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Generate and store the anti-forgery token
            string token = Guid.NewGuid().ToString();
            ViewState["AntiForgeryToken"] = token;
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        // Validate the anti-forgery token
        if (ViewState["AntiForgeryToken"] != null && Request.Form["__RequestVerificationToken"] == ViewState["AntiForgeryToken"].ToString())
        {
            // Token validation succeeded; process the form
            lblMessage.Text = "Form submitted successfully!";
        }
        else
        {
            // Token validation failed; handle the error
            lblMessage.Text = "CSRF attack detected!";
        }
    }
}
 

In this example:

  • The Page_Load event generates an anti-forgery token and stores it in the ViewState. You can also use a session variable or a cookie for this purpose.

  • The btnSubmit_Click event handler validates the anti-forgery token in the request against the token stored in the ViewState. If the validation fails, it displays an error message; if it succeeds, it processes the form submission.

This code demonstrates how to implement CSRF protection in a standard ASP.NET web application without using ASP.NET MVC.