title: How can I generate an antiforgery cookie and token in a controller
body: <p>I'm trying to forge a request from within my application but I can't figure out how to get the antiforgery bit of this to work. I need to support some legacy code which can only really be called via a web request.</p>
  
  <p>I've been able to get a token from the controller by faking a HtmlHelper but when it tries to validate it it gives me this exception:</p>
  
  <p>The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the  configuration specifies explicit encryption and validation keys.</p>
  
  <p>Code to generate the token:</p>
  
  <pre><code>var antiForgeryTokenField = new HtmlHelper(new ViewContext(), new ViewPage()).AntiForgeryToken().ToString();
          var intermediate = antiForgeryTokenField.Substring(antiForgeryTokenField.IndexOf("value=\"") + 8);
          var token = intermediate.Substring(0, intermediate.IndexOf("\""));
  </code></pre>
  
  <p>I'm not sure if its related to the fact that the antiforgery cookie might not be correct?</p>