title: Creating an AntiForgeryToken through Dependency Injection
body: <p>I'm working on improving the security of my company's website and wanted to create a token to prevent forgery attempts that could be easily maintained this is what I came up with.</p>
  
  <pre><code>public class AntiForgeryToken
  {
      private readonly string _referenceToken;
  
      public AntiForgeryToken()
      {
          _referenceToken = Guid.NewGuid().ToString();
      }
      public string ReferenceToken
      {
          get { return _referenceToken; }
      }
  }
  </code></pre>
  
  <p>In my base class for my MasterPage I have a HiddenField wrapped with property named: <code>ReferenceToken</code></p>
  
  <pre><code>protected virtual void Page_Load(object sender, EventArgs e)
  {
      if (!Page.IsPostBack)
      {
          InjectToken();
      }
  
      ValidateToken();
  }
  
  private void InjectToken()
  {
      var token = ObjectFactory.GetInstance&lt;AntiForgeryToken&gt;();
      ReferenceToken = token.ReferenceToken;
  }
  
  private void ValidateToken()
  {
      var token = ObjectFactory.GetInstance&lt;AntiForgeryToken&gt;();
      if (ReferenceToken.Equals(token.ReferenceToken, SC.InvariantCultureIgnoreCase)) 
              return;
      ...do stuff for failed token
  }
  </code></pre>
  
  <p>I have StructureMap handle storing the token inside the Session so it's persisted per user session, would all of this be a valid implementation of an AntiForgery scheme?</p>
  
  <p><strong>Edit:</strong> There seems to be some confusion on my question, yes I understand ASP.NET MVC has a built in AntiForgeryToken scheme, this question is explicitly about how to recreate this for <strong>WebForms</strong> to prevent the usage of a CSRF attack (Cross Site Request Forgery). I understand this in no means removes the need for proper authorization of user rights.</p>
  
  <p>I was going to bring up the very link that @Neal and @solairaja posted: <a href="http://blog.codeville.net/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/" rel="nofollow noreferrer">Prevent Cross-Site Request Forgery (CSRF) using ASP.NET MVC’s AntiForgeryToken() helper</a>. This article explains more of what the CSRF attack is and how MVC stops it however their solution isn't applicable to webforms which is why I went about implementing my own.</p>
  
  <p>After seeing the response from @Neal I think that will most likely be the accepted answer since I didn't realize I could just get the actual source code from the MVC tool which will most likely replace the guid creation. But I'll leave the question open incase anyone else has some valuable information to add.</p>