title: MVC WebApi + Basic Authentication + JSONP cross-domain
body: <p>I'm trying to create an MVC-based site providing some services via WebApi, to both local pages and external clients, thus requiring JSONP to avoid the same origin policy error. The problem is that the site is using Basic authentication, which as I learnt from other posts here cannot play with JSONP. I tried to inject user:pass in the URL, as suggested in the post <a href="https://stackoverflow.com/questions/1640391/how-do-i-make-a-jsonp-call-with-jquery-with-basic-authentication">How do I make a JSONP call with JQuery with Basic Authentication?</a>, but this does not work and the server returns an unauthorized code. Also, I tried just making the call without injecting, as I would be fine in entering username and password in the browser: the browser asks me for the credentials as expected, but then for some reason they are refused, ending into an unauthorized code again. Yet the credentials are OK, as I can confirm by successfully running exactly the same code from the same domain. Could anyone tell me what's wrong with my code?</p>
  
  <p>My MVC WebApi controller action is like:</p>
  
  <pre><code>[BasicAuthorize(Roles = "administrator,customer,trial")]
  public class TextApiController : ApiController
  {
        // ...
  
      public SomeResult Get([FromUri] SomeParams p)
      {
            // some processing which returns a SomeResult object
            //...
      }
  }
  </code></pre>
  
  <p>where the BasicAuthorize attribute is a class I modified from <a href="http://kevin-junghans.blogspot.it/2013/02/mixing-forms-authentication-basic.html" rel="nofollow noreferrer">http://kevin-junghans.blogspot.it/2013/02/mixing-forms-authentication-basic.html</a>, as follows:</p>
  
  <pre><code>[AttributeUsageAttribute(AttributeTargets.Class |
      AttributeTargets.Method, Inherited = true,
      AllowMultiple = true)]
  public sealed class BasicAuthorizeAttribute : AuthorizeAttribute
  {
      static private string DecodeFrom64(string sEncodedData)
      {
          byte[] encodedDataAsBytes = Convert.FromBase64String(sEncodedData);
          return Encoding.ASCII.GetString(encodedDataAsBytes);
      }
  
      static private bool GetUserNameAndPassword(HttpActionContext context,
          out string sUserName,
          out string sPassword,
          out bool bCookieAuthorization)
      {
          bCookieAuthorization = false;
          bool bSuccess = false;
          sUserName = sPassword = "";
          IEnumerable&lt;string&gt; headerVals;
  
          if (context.Request.Headers.TryGetValues("Authorization", out headerVals))
          {
              try
              {
                  string sAuthHeader = headerVals.First();
                  string[] authHeaderTokens = sAuthHeader.Split();
  
                  if (authHeaderTokens[0].Contains("Basic"))
                  {
                      string sDecoded = DecodeFrom64(authHeaderTokens[1]);
                      string[] aPairMembers = sDecoded.Split(new[] { ':' });
                      sUserName = aPairMembers[0];
                      sPassword = aPairMembers[1];
                  } 
                  else
                  {
                      if (authHeaderTokens.Length &gt; 1)
                          sUserName = DecodeFrom64(authHeaderTokens[1]);
                      bCookieAuthorization = true;
                  } 
  
                  bSuccess = true;
              }
              catch
              {
                  bSuccess = false;
              }
          } 
  
          return bSuccess;
      }
  
      static private bool Authenticate(HttpActionContext actionContext,
          out string sUserName)
      {
          bool bIsAuthenticated = false;
          string sPassword;
          bool bCookieAuthorization;
  
          if (GetUserNameAndPassword(actionContext,
              out sUserName, out sPassword, out bCookieAuthorization))
          {
              // if the header tells us we're using Basic auth then log the user in
              if (!bCookieAuthorization)
              {
                  if (WebSecurity.Login(sUserName, sPassword, true))
                      bIsAuthenticated = true;
                  else
                      WebSecurity.Logout();
              } 
              // else get authentication from web security
              else
              {
                  if (WebSecurity.IsAuthenticated) bIsAuthenticated = true;
                  sUserName = WebSecurity.CurrentUserName;
              } 
          } 
          else actionContext.Response =
              new HttpResponseMessage(HttpStatusCode.BadRequest);
  
          return bIsAuthenticated;
      }
  
      private bool IsAuthorized(string sUserName)
      {
          SimpleRoleProvider roles =
              (SimpleRoleProvider)System.Web.Security.Roles.Provider;
            string[] aRoles = Roles.Split(new[] {','});
  
          return (aRoles.Any(sRole =&gt; roles.IsUserInRole(sUserName, sRole)));
      }
  
      public override void OnAuthorization(HttpActionContext actionContext)
      {
          string sUserName;
  
          if (Authenticate(actionContext, out sUserName))
          {
              if (!IsAuthorized(sUserName))
                  actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
          } 
          else
          {
              actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
          } 
      }
  }
  </code></pre>
  
  <p>My client code is a simple HTML page with some Javascript (using jQuery), like:</p>
  
  <pre><code>...
  &lt;form&gt;
      &lt;fieldset&gt;
          &lt;legend&gt;&lt;/legend&gt;
          &lt;ol&gt;
              &lt;li&gt;
                  input text
                  &lt;input type="text" id="input"/&gt;
              &lt;/li&gt;
              &lt;li&gt;
                  username
                  &lt;input type="text" id="user"/&gt;
              &lt;/li&gt;
              &lt;li&gt;
                  password
                  &lt;input type="password" id="password"/&gt;
              &lt;/li&gt;
              &lt;li&gt;&lt;a href="#" id="apip"&gt;API: JSONP&lt;/a&gt;&lt;/li&gt;
          &lt;/ol&gt;
      &lt;/fieldset&gt;
  &lt;/form&gt;
  &lt;div id="result"&gt;&lt;/div&gt;
  &lt;script&gt;
      function getAuthorizationHeader(username, password) {
          "use strict";
          var authType;
  
          if (password == "") {
              authType = "Cookie " + $.base64.encode(username);
          }
          else {
              var up = $.base64.encode(username + ":" + password);
              authType = "Basic " + up;
          };
          return authType;
      };
  
      function ajaxSuccessHandler(data) {
          "use strict";
          $("#result").text(data);
      };
  
      function ajaxErrHandler(jqXHR, textStatus, errorThrown) {
          "use strict";
          $("#result").text(errorThrown + " : " + textStatus);
      }
  
      $(function () {
          "use strict";
  
          $("#apip").click(function () {
              "use strict";
              var text = $("#input").val();
              $.ajax({
                  url: "https://somesiteurl.com/api/wordapi?Text=" + encodeURIComponent(text),
                  dataType: "jsonp",
                  type: "GET",
                  beforeSend: function (xhr) {
                      xhr.setRequestHeader("Authorization", getAuthorizationHeader($("#user").val(), $("#password").val()));
                  },
                  success: ajaxSuccessHandler,
                  error: ajaxErrHandler
              });
          });
      });
  &lt;/script&gt;
  </code></pre>
  
  <h2>CORS</h2>
  
  <p>Sorry for the late response... I'm trying with CORS as suggested, but I'm surely missing something obvious as the headers sent by my client do not include Origin. Here is what I did, by using the library from <a href="http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/" rel="nofollow noreferrer">http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/</a> :</p>
  
  <ol>
  <li><p>I create a new MVC4 internet application to test this scenario, and add Thinktecture.IdentityModel using NuGet.</p></li>
  <li><p>in App_Start I create this CorsConfig class:</p></li>
  </ol>
  
  <p><code><pre>static public class CorsConfig
  {
      public static void RegisterCorsForWebApi(HttpConfiguration httpConfig)
      {
          WebApiCorsConfiguration corsConfig = new WebApiCorsConfiguration();</p>
  
  <pre><code>    // this adds the CorsMessageHandler to the HttpConfiguration’s 
      // MessageHandlers collection
      corsConfig.RegisterGlobal(httpConfig);
  
      corsConfig
          .ForResources("Products")
          .ForOrigins("http://hello.net")
          .AllowAll();
  }
  
  public static void RegisterCorsForMvc(MvcCorsConfiguration corsConfig)
  {
      corsConfig
          .ForResources("Products.GetProducts")
          .ForOrigins("http://hello.net")
          .AllowAll();
  }
  </code></pre>
  
  <p>}
  </pre></code></p>
  
  <ol start="3">
  <li><p>in Global.asax.cs I call both methods of this class.</p></li>
  <li><p>in web.config add:</p>
  
  <p>
    
      
    
  </p></li>
  <li><p>I create a simple action method in a MVC controller returning some JSON. I plan to decorate with [Authorize] later, once the call is placed correctly on the client side, so I can test the authentication (and authorization, adding Roles).</p></li>
  <li><p>in a view, I call my method like:</p></li>
  </ol>
  
  <p><code><pre>var text = $("#input").val();
  var json = "{'text': " + JSON.stringify(text) + "}";
  $.ajax({
      url: "/Home/GetSomeJson",
      dataType: "json",
      data: json,
      type: "GET",
      beforeSend: function (xhr) {
          xhr.withCredentials = true;
      },
      crossDomain: true,
      username: $("#user").val(),
      password: $("#password").val(),
      success: ajaxSuccessHandler,
      error: ajaxErrHandler
  });
  </pre></code>
  Yet, examining the headers I see no origin. Also, is this the correct way of passing credentials (of course in real world this would be HTTPS) for a CORS call to MVC action/WebApi?</p>