locked
setRequestHeader from jQuery ajax for authorization is not adding request header to wcf call RRS feed

  • Question

  • User-1195500931 posted

    Hi,

    I need to pass authorization header to my WCF service to have more security. Please note that it is a cross domain access and I have implemented CORS in wcf service. But the issue is the setRequestHeader(from jQuery ajax call) for authorization is not adding request header to wcf call. Please check the code and let me know where i am wrong.

    IAuthService.cs
    **************

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    using System.ServiceModel.Web;
    
    namespace oAuthWCFService
    {
        [ServiceContract]
        public interface IAuthService
        {
            [OperationContract]
            [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "TestWork")]
            string TestWork();
         }
    }

    AuthService.svc.cs
    ****************

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    using System.ServiceModel.Web;
    using OAuth;
    using System.Collections.Specialized;
    using System.Web;
    using System.IO;
    using System.ServiceModel.Activation;
    
    namespace oAuthWCFService
    {
         [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        public class AuthService : IAuthService
        {
            public string TestWork()
            {
                if (Authenticate(WebOperationContext.Current.IncomingRequest))
                {
                    return "I got it!";
                }
                else
                    return "try later";
            }
    
            private static bool Authenticate(IncomingWebRequestContext context)
            {
                bool Authenticated = false;
                string hdrVal = context.Headers["Authorization"]; //always empty.
                 NameValueCollection pa = context.Headers;
                 foreach (string key in pa.Keys)
                {
                    Logger.log("header " + key + "=" + pa[key]); // Logger note is given below.
                }
                if (hdrVal== "Test")
                {
                       Authenticated = true;
                }
                return Authenticated;
            }
       }

      Global.asax
    *************

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.SessionState;
    
    namespace oAuthWCFService
    {
        public class Global : System.Web.HttpApplication
        {
            protected void Application_Start(object sender, EventArgs e)
            {
            }
    
            protected void Session_Start(object sender, EventArgs e)
            {
            }
    
            protected void Application_BeginRequest(object sender, EventArgs e)
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
                if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
                {
                    HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
    
                    //For GET
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                    //For POST
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, x-requested-with");
    
                    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                    HttpContext.Current.Response.End();
                }
            }
    
            protected void Application_AuthenticateRequest(object sender, EventArgs e)
            {
            }
            protected void Application_Error(object sender, EventArgs e)
            {
            }
            protected void Session_End(object sender, EventArgs e)
            {
            }
            protected void Application_End(object sender, EventArgs e)
            {
    
            }
        }
    }

    web.config
    *************

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
    
      <system.web>
        <compilation debug="true" targetFramework="4.0" />
      </system.web>
      <system.serviceModel>
    
        <behaviors>
          <serviceBehaviors>
            <behavior>
              <serviceMetadata httpGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
            <behavior name="webHttpBehavior">
            </behavior>
          </endpointBehaviors>
        </behaviors>
    
        <bindings>
          <webHttpBinding>
           <binding name="oAuthWebHttpBinding" crossDomainScriptAccessEnabled="true">
            </binding>
          </webHttpBinding>
        </bindings>
    
        <services>
          <service name="oAuthWCFService.AuthService">
            <endpoint address="" behaviorConfiguration="webHttpBehavior" binding="webHttpBinding" bindingConfiguration="oAuthWebHttpBinding" contract="oAuthWCFService.IAuthService" />
           </service>
        </services>
           <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
      </system.serviceModel>
      <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
            <directoryBrowse enabled="true" />
      </system.webServer>
    </configuration>

    jQuery ajax call
    ****************

    function corsClick() {
                $.support.cors = true;
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json;charset=utf-8",
                    url: "http://mydomain:84/AuthService.svc/TestWork",
                                    beforeSend: function (jqXHR, settings) {
                                         var auth = "Test";
                                        $.extend(settings, { headers: { "Authorization": auth} });
                                    },
                   success: function (msg) {
                        alert(JSON.stringify(msg));
                    },
                    error: function () {
                        alert("Network error");
                    }
                });
            }

    Logger note:
    ************

     header Cache-Control=no-cache
    
     header Connection=keep-alive
    
     header Pragma=no-cache
    
     header Content-Length=0
    
    header Content-Type=application/json;charset=utf-8
    
     header Accept=application/json, text/javascript, */*; q=0.01
    
     header Accept-Encoding=gzip, deflate
    
     header Accept-Language=en-US,en;q=0.5
    
     header Host=192.168.5.109:84
    
     header Referer=http://localhost:50560/VS%20Using%20KendoUIMobile/NewAuth.htm
    
    header User-Agent=Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0
    
    header DNT=1
    
    header Origin=http://localhost:50560

    Thanks.






    Wednesday, July 17, 2013 8:54 AM

Answers

  • User-1195500931 posted

    Hi,

    I was able to solve the issue. I have added the Authorization header into "Access-Control-Allow-Headers" and it solved the issue.

    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");

    Thanks.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 24, 2013 5:10 AM