title: SimpleMembership in MVC4 app + WebApi using basic HTTP auth
body: <p>I'm trying to implement an MVC4 web application with the following requirements:</p>
  
  <p>(a) it offers its services to authenticated users only. As for authentication, I'd like to use simple membership, as it is the latest authentication technique from MVC, gives me the advantage of defining my own db tables, provides OAuth support out of the box, and is easily integrated with both MVC and WebApi.</p>
  
  <p>(b) it exposes some core functions via WebApi for mobile/JS clients, which should be authenticated via basic HTTP authentication (+SSL). Typically I'll have JS clients using jQuery AJAX calls to WebApi controllers, decorated with the Authorize attribute for different user roles.</p>
  
  <p>(c) ideally, in a mixed environment I would like to avoid a double authentication: i.e. if the user is already authenticated via browser, and is visiting a page implying a JS call to a WebApi controller action, the (a) mechanism should be enough.</p>
  
  <p>Thus, while (a) is covered by the default MVC template, (b) requires basic HTTP authentication without the mediation of a browser. To this end, I should create a DelegatingHandler like the one I found in this post: <a href="http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-message-handlers">http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-message-handlers</a>. 
  The problem is that its implementation requires some way of retrieving an IPrincipal from the received user name and password, and the WebSecurity class does not provide any method for this (except Login, but I would avoid changing the logged user just for the purpose of authorization, also because of potential "mixed" environments like (c)). So it seems my only option is giving up simple membership. Does anyone have better suggestions? Here is the relevant (slightly modified) code from the cited post:</p>
  
  <pre><code>public interface IPrincipalProvider
  {
      IPrincipal GetPrincipal(string username, string password);
  }
  
  public sealed class Credentials
  {
      public string Username { get; set; }
      public string Password { get; set; }
  }
  
  public class BasicAuthMessageHandler : DelegatingHandler
  {
      private const string BasicAuthResponseHeader = "WWW-Authenticate";
      private const string BasicAuthResponseHeaderValue = "Basic";
  
      public IPrincipalProvider PrincipalProvider { get; private set; }
  
      public BasicAuthMessageHandler(IPrincipalProvider provider)
      {
          if (provider == null) throw new ArgumentNullException("provider");
          PrincipalProvider = provider;
      }
  
      private static Credentials ParseAuthorizationHeader(string sHeader)
      {
          string[] credentials = Encoding.ASCII.GetString(
              Convert.FromBase64String(sHeader)).Split(new[] { ':' });
  
          if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) ||
              String.IsNullOrEmpty(credentials[1])) return null;
  
          return new Credentials
          {
              Username = credentials[0],
              Password = credentials[1],
          };
      }
  
      protected override System.Threading.Tasks.Task&lt;HttpResponseMessage&gt; SendAsync(
          HttpRequestMessage request,
          CancellationToken cancellationToken)
      {
          AuthenticationHeaderValue authValue = request.Headers.Authorization;
          if (authValue != null &amp;&amp; !String.IsNullOrWhiteSpace(authValue.Parameter))
          {
              Credentials parsedCredentials = ParseAuthorizationHeader(authValue.Parameter);
              if (parsedCredentials != null)
              {
                  Thread.CurrentPrincipal = PrincipalProvider
                      .GetPrincipal(parsedCredentials.Username, parsedCredentials.Password);
              } 
          } 
  
          return base.SendAsync(request, cancellationToken)
              .ContinueWith(task =&gt;
              {
                  var response = task.Result;
                  if (response.StatusCode == HttpStatusCode.Unauthorized
                      &amp;&amp; !response.Headers.Contains(BasicAuthResponseHeader))
                  {
                      response.Headers.Add(BasicAuthResponseHeader,
                          BasicAuthResponseHeaderValue);
                  } 
                  return response;
              });
      }
  }
  </code></pre>