title: Orchard CMS Ajax Anti-Forgery Token When Logged In
body: <p>I am building an Orchard CMS module that I am testing on an Orchard 1.3.10 site.  The module displays a details view for one of my entities and I have a "favorites" button that I would like to click and do an ajax post to a controller action to save the entity as a favorite in the database.</p>
  
  <p>On the view I have the following code:</p>
  
  <pre><code>&lt;div style="padding: 10px;"&gt;
      &lt;span data-id="@Model.Id" id="addFavorite" style="cursor: pointer;"&gt;
      [Add Favorite]
      &lt;/span&gt;
  &lt;/div&gt;
  
  &lt;script type="text/javascript"&gt;
      $("#addFavorite").click(function () {
          alert("here we go...");
          $.ajax({
              type: "post",
              dataType: "",
              url: "/orchardlocal/mymodule/stuff/AddFavorite",
              data: { id: $(this).data("id") },
              success: function (response) {
                  alert("it worked");
              }
          });
      });
  &lt;/script&gt;
  </code></pre>
  
  <p>My controller action is...</p>
  
  <pre><code>[HttpPost]
  public ActionResult AddFavorite(int id)
  {
      return View();
  }
  </code></pre>
  
  <p>When I run the site without being logged into Orchard, this code posts back just fine.  If I log in and click on Add Favorite, I get this exception... </p>
  
  <blockquote>
    <p>A required anti-forgery token was not supplied or was invalid.</p>
    
    <p>System.Web.Mvc.HttpAntiForgeryException was unhandled by user code
      Message=A required anti-forgery token was not supplied or was invalid.
      Source=System.Web.WebPages
      ErrorCode=-2147467259
      WebEventCode=0
      StackTrace:
           at System.Web.Helpers.AntiForgeryWorker.Validate(HttpContextBase context, String salt)
           at System.Web.Helpers.AntiForgery.Validate(HttpContextBase httpContext, String salt)
           at System.Web.Mvc.ValidateAntiForgeryTokenAttribute.OnAuthorization(AuthorizationContext > filterContext)
           at Orchard.Mvc.AntiForgery.AntiForgeryAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext) in C:\Code\OrchardDev2\src\Orchard\Mvc\AntiForgery\AntiForgeryAuthorizationFilter.cs:line 37
           at System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor)
           at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
      InnerException: </p>
  </blockquote>
  
  <p>Why does it treat the post differently when logged in and not?</p>
  
  <p>How can I supply an anti-forger token to avoid this?</p>
  
  <p>Thanks,
  Brian</p>