title: Web Api Cross Domain Basic Authentication
body: <p>I have setup a web api to allow cross domain access with Basic Authentication. When I make a cross domain GET request to the API, it works fine and I am getting token in "Authorization" header in my custom message handler. But when initiating a cross domain POST request, I am not getting the "Authorization" header that's why unable to validate the request. </p>
  
  <p>Any help would be highly appreciated.</p>
  
  <p>Following is the code for my custom message handler for cross domain access.</p>
  
  <pre><code>    using System;
      using System.Linq;
      using System.Net;
      using System.Net.Http;
      using System.Threading;
      using System.Threading.Tasks;
  
      namespace MyWebApi.Handlers
      {
          public class XHttpMethodOverrideDelegatingHandler : DelegatingHandler
          {
              static readonly string[] HttpOverrideMethods = { "PUT", "DELETE" };
              static readonly string[] AccessControlAllowMethods = { "POST", "PUT", "DELETE" };
              private const string HttpMethodOverrideHeader = "X-HTTP-Method-Override";
              private const string OriginHeader = "ORIGIN";
              private const string AccessControlAllowOriginHeader = "Access-Control-Allow-Origin";
              private const string AccessControlAllowMethodsHeader = "Access-Control-Allow-Methods";
              private const string AccessControlAllowHeadersHeader = "Access-Control-Allow-Headers";
  
              protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
              {
  
  
                   var authHeader = request.Headers.Authorization;
  
                  if (authHeader == null || authHeader.Scheme != "Basic" || string.IsNullOrWhiteSpace(authHeader.Parameter))
                  {
                      return CreateUnauthorizedResponse();
                  }
  
                  if (request.Method == HttpMethod.Post &amp;&amp; request.Headers.Contains(HttpMethodOverrideHeader))
                  {
                      var httpMethod = request.Headers.GetValues(HttpMethodOverrideHeader).FirstOrDefault();
                      if (HttpOverrideMethods.Contains(httpMethod, StringComparer.InvariantCultureIgnoreCase))
                          request.Method = new HttpMethod(httpMethod);
                  }
  
                  var httpResponseMessage = base.SendAsync(request, cancellationToken);
  
                  if (request.Method == HttpMethod.Options &amp;&amp; request.Headers.Contains(OriginHeader))
                  {
                      httpResponseMessage.Result.Headers.Add(AccessControlAllowOriginHeader, request.Headers.GetValues(OriginHeader).FirstOrDefault());
                      httpResponseMessage.Result.Headers.Add(AccessControlAllowMethodsHeader, String.Join(", ", AccessControlAllowMethods));
                      httpResponseMessage.Result.Headers.Add(AccessControlAllowHeadersHeader, HttpMethodOverrideHeader);
                      httpResponseMessage.Result.StatusCode = HttpStatusCode.OK;
                  }
                  //No mater what the HttpMethod (POST, PUT, DELETE), if a Origin Header exists, we need to take care of it
                  else if (request.Headers.Contains(OriginHeader))
                  {
                      httpResponseMessage.Result.Headers.Add(AccessControlAllowOriginHeader, request.Headers.GetValues(OriginHeader).FirstOrDefault());
                  }
  
                  return httpResponseMessage;
              }
  
              private Task&lt;HttpResponseMessage&gt; CreateUnauthorizedResponse()
              {
                  var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                  response.Headers.Add("WWW-Authenticate", "Basic");
  
                  var taskCompletionSource = new TaskCompletionSource&lt;HttpResponseMessage&gt;();
                  taskCompletionSource.SetResult(response);
                  return taskCompletionSource.Task;
              }
          }
      }
  </code></pre>
  
  <p>And i have registered the above handler in Application_Start as follows:</p>
  
  <pre><code>    namespace MyWebApi
      {
          public class Global : System.Web.HttpApplication
          {
              protected void Application_Start(object sender, EventArgs e)
              {
                  RouteTable.Routes.MapHttpRoute(
                      name: "DefaultApi",
                      routeTemplate: "api/{controller}/{action}/{id}",
                      defaults: new {id = RouteParameter.Optional});
                  GlobalConfiguration.Configuration.MessageHandlers.Add(new XHttpMethodOverrideDelegatingHandler()); 
                  GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter());
              }
          }
      }
  </code></pre>
  
  <p>At client side on a different domain project, I am trying to add a new record using following code.</p>
  
  <pre><code>     AddUser {
  
                  var jsonData = {
                      "FirstName":"My First Name",
                      "LastName": "My Last Name",
                      "Email": "my.name@mydomain.com",
                      "Password": "MyPa$$word"
                  };
  
                  $.ajax({
                      type: "POST",
                      dataType: 'json',
                      url: "http://localhost:4655/api/user/signup",
                      beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic xxxxxxxxxxxxxx"); },
                      accept: "application/json",
                      data: JSON.stringify(jsonData),
                      success: function (data) {
                          alert("success");
                      },
                      failure: function (errorMsg) {
                          alert(errorMsg);
  
                      },
                      error: function (onErrorMsg) {
                          alert(onErrorMsg.statusText);
                      },
                      statusCode: function (test) {
                          alert("status");
                      }
                  });
              });
  </code></pre>
  
  <p>And following is the code for my user controller.</p>
  
  <pre><code>    namespace MyWebApi.Controllers
      {
          public class UserController : ApiController
          {
  
              [HttpPost]
              [ActionName("Adduser")]
              public int Post(UserModel source)
              {
                      if (source == null)
                      {
                          throw new ArgumentNullException("source");
                      }
                      Db.Users.Add(source);
                      Db.SaveChanges();
  
                      return source.UserId;
              }                
          }
      }
  </code></pre>
  
  <p>Thanks in advance!</p>