Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am creating CSRF Token Cookie as part of the security fix against csrf forgery attack. Token is visible in the request headers and not in the response headers while checking via developer tools and hence there is a chance of information leakage.

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Cache-Control: max-age=0
Connection: keep-alive
Cookie: .ASPXAUTH=; ASP.NET_SessionId=b1tud33l5vsixs5sm1dgxpay; __AntiXsrfToken=7d38e61dee524d74af2918c643cb1554


What I have tried:

I am setting CSRF Token Cookie as below:

C#
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);
                 
                }
Posted
Updated 4-May-22 8:44am
v2

1 solution

Don't try to roll your own, especially since you don't seem to be particularly sure of what you're doing.

Microsoft already provide an anti-XSRF library you can use:
XSRF/CSRF Prevention in ASP.NET MVC and Web Pages | Microsoft Docs[^]
Preventing Cross-Site Request Forgery (CSRF) Attacks in ASP.NET MVC | Microsoft Docs[^]

Although the Microsoft links only mention MVC and WebPages, you can still use the library from a WebForms project:
How to prevent xsf/csrf attacks in ASP.NET webforms only?[^]
 
Share this answer
 

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