title: WCF service and oauth + jQuery ajax call
body: <p>I was trying to implement oauth authentication in my WCF service. I am doing the service call from jQuery ajax. I have tried the following code in CORS enabled service with POST verb. But here I am getting pa["oauth_consumer_key"] as always null. Please see the code and help me to find out the issue.</p>
  
  <p>Using POST and CORS</p>
  
  <hr>
  
  <p>jQuery ajax call:-</p>
  
  <pre><code> function logClick() {
              var sEmail = $('#username').val();
              var sPassword = $('#password').val();
              var key = "test";
              var oauth_signature = "xxxxxxx";
              var timestamp = (new Date()).getTime();
              var nonce = Math.random();
              var auth_header = 'OAuth oauth_nonce="' + nonce + '"' +
              ', oauth_signature_method="HMAC-SHA1"' +
              ', oauth_timestamp="' + timestamp + '"' +
              ', oauth_consumer_key="' + key + '"' +
              ', oauth_signature="' + oauth_signature + '"' +
              ', oauth_version="1.0"';
  
              var userData = '{"email":"' + sEmail + '","password":"' + sPassword + '"}';
              $.support.cors = true;
              $.ajax({
                  data: userData,
                  type: "POST",
                  dataType: "json",
                  contentType: "application/json;charset=utf-8",
                  url: "http://mydomain/MyAppService.svc/UserValidation",
                  beforeSend : function(xhr, settings) {
                            $.extend(settings, { headers : { "Authorization": auth_header } });
                },
                  success: function (msg) {
                     alert("success");
                  },
                  error: function () {
                      alert("Network error");
                  }
              });
          }
  </code></pre>
  
  <p>WCF service code</p>
  
  <pre><code>  [OperationContract]
          [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "UserValidation")]
          int UserValidation(string email,string password);
  
  
       public int UserValidation(string email, string password)
      {
  
          if (Authenticate(WebOperationContext.Current.IncomingRequest))
          {
              //my code
               return 1;
          }
          else
          {
              return 0;
          }
      }
  
      private static bool Authenticate(IncomingWebRequestContext context)
      {
  
          bool Authenticated = false;
          string normalizedUrl;
          string normalizedRequestParameters;
  
          NameValueCollection pa = context.Headers; 
          //NameValueCollection pa = context.UriTemplateMatch.QueryParameters;// tried this also
          if (pa != null &amp;&amp; pa["oauth_consumer_key"] != null)  // pa["oauth_consumer_key"] is always null
          {
                // to get uri without oauth parameters
              string uri = context.UriTemplateMatch.RequestUri.OriginalString.Replace
                  (context.UriTemplateMatch.RequestUri.Query, "");
              string consumersecret = "suryabhai";
              OAuthBase oauth = new OAuthBase();
              string hash = oauth.GenerateSignature(
                  new Uri(uri),
                  pa["oauth_consumer_key"],
                  consumersecret,
                  null, // totken
                  null, //token secret
                  "GET",
                  pa["oauth_timestamp"],
                  pa["oauth_nonce"],
                  out normalizedUrl,
                  out normalizedRequestParameters
                  );
  
              Authenticated = pa["oauth_signature"] == hash;
           }
          return Authenticated;
  
      }
  </code></pre>
  
  <p>I did the same aouth authentication in GET and JSONP . Following is the code. Here the authentication is working, but I am not getting the result even though the service return data. ( entering to error block in jQuery ajax call)</p>
  
  <p>GET and JSONP</p>
  
  <hr>
  
  <p>jQuery ajax call:-</p>
  
  <pre><code>function getData() {
  
              $.ajax({
                    url: "http://mydomain/MyAppService.svc/GetData/328?oauth_consumer_key=test&amp;oauth_nonce=10a33ed37b549301644b23b93fc1f1c5&amp;oauth_signature=AMTsweMaWeN7kGnSwoAW44WKUuM=&amp;oauth_signature_method=HMAC-SHA1&amp;oauth_timestamp=1289976718&amp;oauth_version=1.0?callback=?",
                  type: "GET",
                  crossDomain: true,
                  contentType: "application/json; charset=utf-8",
                  dataType: "jsonp",
                  processdata: true,
                  success: function (msg) {
                      alert("success");
  
                  },
                  error: function error(response) {
                      alert(" Network Error"); // always entering to this block
                  }
              });
  </code></pre>
  
  <p>WCF service :-</p>
  
  <pre><code> [OperationContract]
          [WebInvoke(Method = "GET",
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Bare,
    UriTemplate = "GetData/{ParentID}")]
          List&lt;Parent&gt; GetData(string ParentID);
  
  
   public List&lt;Parent&gt; GetData(string ParentID)
          {
               List&lt;Parent&gt; ParentList = new List&lt;Parent&gt;();
              if (Authenticate(WebOperationContext.Current.IncomingRequest)) // it is working
             {
                  //my code
                return ParentList ; // result is getting, but on client it is going to error block of jQUery ajax call
             }
              else
              {
                  return ParentList ;
              }
          }
  
  private static bool Authenticate(IncomingWebRequestContext context)
          {
  
              bool Authenticated = false;
              string normalizedUrl;
              string normalizedRequestParameters;
              NameValueCollection pa = context.UriTemplateMatch.QueryParameters;
              if (pa != null &amp;&amp; pa["oauth_consumer_key"] != null)  
              {
                    // to get uri without oauth parameters
                  string uri = context.UriTemplateMatch.RequestUri.OriginalString.Replace
                      (context.UriTemplateMatch.RequestUri.Query, "");
                  string consumersecret = "suryabhai";
                  OAuthBase oauth = new OAuthBase();
                  string hash = oauth.GenerateSignature(
                      new Uri(uri),
                      pa["oauth_consumer_key"],
                      consumersecret,
                      null, // totken
                      null, //token secret
                      "GET",
                      pa["oauth_timestamp"],
                      pa["oauth_nonce"],
                      out normalizedUrl,
                      out normalizedRequestParameters
                      );
  
                  Authenticated = pa["oauth_signature"] == hash;
               }
              return Authenticated;
  
          }
  </code></pre>
  
  <p>Web.config:-</p>
  
  <pre><code>&lt;?xml version="1.0"?&gt;
  &lt;configuration&gt;
  
    &lt;system.web&gt;
      &lt;authentication mode="None" /&gt;
      &lt;httpRuntime maxRequestLength="2147483647"/&gt;
      &lt;compilation debug="true" targetFramework="4.0" /&gt;
    &lt;/system.web&gt;
    &lt;system.serviceModel&gt;
        &lt;serviceHostingEnvironment multipleSiteBindingsEnabled="true"  aspNetCompatibilityEnabled="true"/&gt;
      &lt;services&gt;
        &lt;service name="DataAppAppService.MyAppService"&gt;
          &lt;endpoint address="" behaviorConfiguration="webHttpBehavior" binding="webHttpBinding" bindingConfiguration="WebHttpBindingWithJsonP" contract=DataAppAppService.IMyAppService" /&gt;
        &lt;/service&gt;
      &lt;/services&gt;
  
      &lt;bindings&gt;
        &lt;webHttpBinding&gt;
          &lt;binding name="WebHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true"  maxReceivedMessageSize="2147483647"
                     maxBufferSize="2147483647" transferMode="Streamed"
                &gt;
  
          &lt;/binding&gt;
  
        &lt;/webHttpBinding&gt;
      &lt;/bindings&gt;
  
      &lt;behaviors&gt;
        &lt;endpointBehaviors&gt;
          &lt;behavior name="webHttpBehavior"&gt;
            &lt;webHttp helpEnabled="true" /&gt;
          &lt;/behavior&gt;
        &lt;/endpointBehaviors&gt;
        &lt;serviceBehaviors&gt;
          &lt;behavior&gt;
            &lt;serviceMetadata httpGetEnabled="true" /&gt;
            &lt;serviceDebug includeExceptionDetailInFaults="true" /&gt;
            &lt;serviceThrottling maxConcurrentCalls="30" maxConcurrentInstances="30" /&gt;
          &lt;/behavior&gt;
        &lt;/serviceBehaviors&gt;
      &lt;/behaviors&gt;
  
    &lt;/system.serviceModel&gt;
  
    &lt;system.webServer&gt;
      &lt;modules runAllManagedModulesForAllRequests="true" /&gt;
      &lt;directoryBrowse enabled="true" /&gt;
    &lt;/system.webServer&gt;
  
  &lt;/configuration&gt;
  </code></pre>