Click here to Skip to main content
14,881,706 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Could you please assist how to prevent xsrf in my form

below is my code that i have tried but AntiForgery.Validate(); thowing exception

What I have tried:

I have tried
C#
protected void Page_Init(object sender, EventArgs e)
{
    AntiForgery.GetHtml();
}
protected void Page_Load(object sender, EventArgs e)
{
    AntiForgery.Validate();
}

AntiForgery.Validate(); Getting exception that missing __RequestVerificationToken.

Could you please assist, Is this approach proper or Correct for these xsrf attacks or any standardized better approach is there?
Posted
Updated 5-Feb-21 1:35am
v2

1 solution

The AntiForgery.GetHtml method[^] returns a string containing the HTML which you need to append to your <form>. You are throwing that string away, so your <form> doesn't contain the anti-XSRF token.

You need to add the HTML to your form:
ASPX
<form runat="server" method="post">
    <%= System.Web.Helpers.AntiForgery.GetHtml() %>
Or:
ASPX
<form runat="server" method="post">
    <asp:literal id="AntiForgeryToken" runat="server" />
C#
protected void Page_Init(object sender, EventArgs e)
{
    AntiForgeryToken.Text = AntiForgery.GetHtml().ToHtmlString();
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900