Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I need to implement CSRF in asp.net web forms to prevent unwanted cross site request.

[edit]Added the word "Protection" to subject line to prevent "malicious coder" kicking, and added code block to "What have you tried" section - OriginalGriff[/edit]

What I have tried:

I have tried below code to implement CSRF but it did not work for me.
C#
public class CSRFBASE : System.Web.UI.Page
    {
        private const string AntiXsrfTokenKey = "__AntiXsrfToken";
        private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
        private string _antiXsrfTokenValue;
        protected void Page_Init(object sender, EventArgs e)
        {
            // The code below helps to protect against XSRF attacks
            var requestCookie = Request.Cookies[AntiXsrfTokenKey];
            Guid requestCookieGuidValue;
            if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
            {
                // Use the Anti-XSRF token from the cookie
                _antiXsrfTokenValue = requestCookie.Value;
                Page.ViewStateUserKey = _antiXsrfTokenValue;
            }
            else
            {
                // Generate a new Anti-XSRF token and save to the cookie
                _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
                Page.ViewStateUserKey = _antiXsrfTokenValue;

                var responseCookie = new HttpCookie(AntiXsrfTokenKey)
                {
                    HttpOnly = true,
                    Value = _antiXsrfTokenValue
                };
                if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
                {
                    responseCookie.Secure = true;
                }
                Response.Cookies.Set(responseCookie);
            }

            Page.PreLoad += master_Page_PreLoad;
        }

        protected void master_Page_PreLoad(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Set Anti-XSRF token
                ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
                ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
            }
            else
            {
                // Validate the Anti-XSRF token
                if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                    || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
                {
                    throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
                }
            }
        }
    }
Posted
Updated 22-Apr-20 20:52pm
v2
Comments
Kornfeld Eliyahu Peter 9-Aug-17 9:17am    
Do you mean you want to implement protection from CSRF?!
Dev_TechnoLabs 9-Aug-17 9:18am    
Yes

Use the below code:

In Design Page:
<div id="DivCSRF" runat="server"></div>

In Code Page:
Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
        DivCSRF.InnerHtml = AntiForgery.GetHtml().ToString()
    End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        DivCSRF.InnerHtml = AntiForgery.GetHtml().ToString()
        If IsPostBack Then
            Try
                AntiForgery.Validate()
            Catch ex As Exception
                Response.Redirect("~/Unauthorize.aspx", False)
                Exit Sub
            End Try
        End If
 
Share this answer
 
v2
 
Share this answer
 
Comments
Dev_TechnoLabs 9-Aug-17 9:27am    
most of the links are related to MVC. not useful for me
Kornfeld Eliyahu Peter 9-Aug-17 9:31am    
Learning is always useful!!! If not other, than the existence of other technologies beyond WebForms...
And the last two (especially the last) is exactly what you are looking for... including exact code sample...
F-ES Sitecore 9-Aug-17 9:31am    
So google "asp.net csfr protection webforms" or ""asp.net csfr protection webforms -mvc". Believe it or not you're not the first person to want to do this so the code is readily available if you just look for it.
Dev_TechnoLabs 6-Oct-17 7:24am    
@F-ES Sitecore thanks for your good suggestion. I will definitely do that.

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