Anti CSRF Token – ASP.NET

  1. Download AntiCSRF from the CSRF module for ASP.NET.
  2. In Project place Idunno.AntiCsrf.dll in Bin folder.
  3. Add a reference to the module into your web.config

 For IIS6/IIS7 in Classic ASP.NET mode:

  <system.web>
          
        <httpModules>            
            <add name="AntiCSRF" type="Idunno.AntiCsrf.AntiCsrfModule, Idunno.AntiCsrf"/>
        </httpModules>
                
  </system.web>

For IIS7 in integrated pipeline mode:

  <system.webmodules>
                  
       <modules>
          <add name="AntiCSRF" type="Idunno.AntiCsrf.AntiCsrfModule, Idunno.AntiCsrf"/>
       </modules>
                  
  </system.webmodules>

4. Add the following settings to web.config

  <configuration>
   
    <configSections>
        
        <section name="csrfSettings"  type="Idunno.AntiCsrf.Configuration.CsrfSettings, Idunno.AntiCsrf" />   
        
    </configSections>
    <csrfSettings cookieName="__CSRFCOOKIE" formFieldName="__CSRFTOKEN" detectionResult="RaiseException" errorPage="" />
  
 </configuration>  

5. Add the following codes in Page_Load Event.

   protected void Page_Load(object sender, EventArgs e)
   {
    string page_name = System.IO.Path.GetFileName(System.
    Web.HttpContext.Current.Request.Url.AbsolutePath);
    string page_token = page_name + "_ID";
    Session[page_token] = CSRF_Token; 
    HiddenField1.value = CSRF_Token;
   }

6. Add the following codes in Any Event.

   protected void Button1_Click(object sender, EventArgs e)
   {
    string Page_Token =   System.IO.Path.GetFileName(System.Web.HttpContext.Current.Request.Url.AbsolutePath)+"_ID";
  
       if (HiddenField1.Value.ToString() != Session[Page_Token].ToString())
       {
          Session.Abandon();
          Session.Clear();
          Response.Redirect("default.aspx");
       }
   }

References

http://anticsrf.codeplex.com/
http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-(csrf)-attacks
https://www.owasp.org/index.php/.Net_CSRF_Guard

2 replies
  1. dude79
    dude79 says:

    The above code doesn’t compile. In the page load, the variable CSRF_Token isn’t defined. Where is the variable coming from and value coming from?

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply to Suraj Cancel reply

Your email address will not be published. Required fields are marked *