title: ASP.NET MVC5 Basic HTTP authentication and AntiForgeryToken exception
body: <p>I'm working on ASP.NET MVC5 project which has forms authentication enabled. Project is currently in test phase, and hosted online on Azure, but project owner would like to disable all public access to the site (since some parts of site don't require for user to authenticate at all).  </p>
  
  <p>For this test phase, we've decided to implement basic HTTP authentication, from this <a href="https://stackoverflow.com/questions/1606991/asp-net-mvc-http-authentication-prompt/1607546#1607546">link</a>. I've changed the code, so it better suits my needs:</p>
  
  <pre><code>public class BasicAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
  {
      public string BasicRealm { get; set; }
  
      protected string Username { get; set; }
      protected string Password { get; set; }
  
      public BasicAuthenticationAttribute(string username, string password)
      {
          this.Username = username;
          this.Password = password;
      }
  
      public void OnAuthorization (AuthorizationContext filterContext)
      {
          var req = filterContext.HttpContext.Request;
          var auth = req.Headers["Authorization"];
          if (!String.IsNullOrEmpty(auth))
          {
              var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':');
              var user = new { Name = cred[0], Pass = cred[1] };
  
              if (user.Name == Username &amp;&amp; user.Pass == Password) 
                  return;
          }
  
          var res = filterContext.HttpContext.Response;
          var alreadySent = HttpContext.Current.Items.Contains("headers-sent");
  
          if (!alreadySent)
          {
              res = filterContext.HttpContext.Response;
              res.StatusCode = 401;
              res.AppendHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Test"));
  
          }
      }
  }
  </code></pre>
  
  <p>I've also registered it as a global filter:</p>
  
  <pre><code>public class FilterConfig
  {
      public static void RegisterGlobalFilters(GlobalFilterCollection filters)
      {
          filters.Add(new HandleErrorExtendedAttribute());
          filters.Add(new BasicAuthenticationAttribute(AppConfig.BasicUsername, AppConfig.BasicPassword));
      }
  }
  </code></pre>
  
  <p>However, there are some issues when I run the project. If I use this version of code:</p>
  
  <pre><code>        if (!alreadySent)
          {
              res = filterContext.HttpContext.Response;
              res.StatusCode = 401;
              res.AppendHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Test"));
          }
  </code></pre>
  
  <p>after successfull login it constantly redirects to forms login page. </p>
  
  <p>However if I append</p>
  
  <pre><code>res.End();
  </code></pre>
  
  <p>after </p>
  
  <pre><code>res.AppendHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Test"));
  </code></pre>
  
  <p>Antiforgerytoken in cshtml files throws System.Web.HttpException</p>
  
  <blockquote>
    <blockquote>
      <p>Server cannot append header after HTTP headers have been sent.</p>
    </blockquote>
  </blockquote>
  
  <p>But in this case, it eventually successfully authenticates. </p>
  
  <p>I'm currently stuck on this, and have no idea how to solve this problem, since turning off forms authentication is not and option, and I can't remove all AntiForgeryTokens and their validation. </p>