Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am doing CSRF Attack prevention in asp.net with c#. Currently I am setting the AntiXSRF token value is generated via GUID and stored in the response cookie headers. I want to store/validate the CSRF Token without storing in the request/response cookie headers.

What I have tried:

Code is as below:
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);
          }
Posted
Updated 17-Jan-22 1:32am
v2
Comments
Richard Deeming 17-Jan-22 8:00am    
Why? That's precisely how every anti-XSRF system works, so what makes you think it's not appropriate for your site?

Even if you move the token into session storage, you still need to send a cookie to identify the session, so you don't gain anything.

If you're worried about cookies being stolen or intercepted, make sure your site is only served over HTTPS. That way, nobody sat between your server and your user can see or tamper with the traffic.
Member 15421351 17-Jan-22 10:04am    
I want to hide the cookie for Antixsrf token from the response headers section even without using https.
Richard Deeming 17-Jan-22 10:27am    
Why? You want to prevent cross-site request forgery, but you DON'T want to protect your users' data in-transit?

Just ditch the XSRF protection if you really care so little about your users...

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