Home > AJAX, WCF > Cross Domain WCF service Call using AJAX / Ajax Call to HTTPS service from HTTP page (With JSONP)

Cross Domain WCF service Call using AJAX / Ajax Call to HTTPS service from HTTP page (With JSONP)

February 23, 2012 Leave a comment Go to comments

I was going to implement SSL login for a mobile web site. The implementation was like that, we will invoke a WCF service and the user will then be logged in to the service hosted in IIS.
To make the service asp.net authentication compatible we have used attribute bellow in the service.

 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]

The problem was that we have used http protocol to load the login page and we have to call a separate service using https(SSL).Which creates cross site http requests.

Cross-site HTTP requests:
Cross-site HTTP requests are HTTP requests for resources from a different domain than the domain of the resource making the request. For instance, a resource loaded from Domain A (http://domaina.example) such as an HTML web page, makes a request for a resource on Domain B (http://domainb.foo), such as an image, using the img element (http://domainb.foo/image.jpg).
You can learn detail from here

https://developer.mozilla.org/en/http_access_control

To solve this problem we have to use JSonp instead of JSon.
JSONP or “JSON with padding” is a complement to the base JavaScript Object Notation JSON data format. It provides a method to request data from a server in a different domain, something prohibited by typical web browsers because of the Same origin policy.

Bellow I am describing the workthrough I have followed.

Step 1:
1. Create a self signed certificate in your IIS
a. Server Certificates – > Create Self Signed Certificate(right side) -> Enter a name(Service1) ->Ok
2. Website (Default Web Site) – >(Right Click Menu) -> edit Bindings-> Add-> Select “Https” in Type -> Specify IP-> Select certificate you have created (Service1) in the SSL Certificate dropdown -> Ok

Step2:
To make WCF service to support SSL (https) we need to set Security Mode=”Transport”

<binding name="DefaultBindingSSL">
    <security mode="Transport">
      </security>
</binding>

<service name="Service1">
        <endpoint address="" behaviorConfiguration="RESTFriendly" binding="webHttpBinding" bindingConfiguration="DefaultBindingSSL" contract="Sentrana.SpoonBytePro.IEnterAppService" />
</service>

Step 3:
In the service we have to write the response in the following way

var context = HttpContext.Current;
      	string Callback = context.Request.QueryString["callback"];
      JsonSerializer ser = new JsonSerializer();
context.Response.Write(Callback + "(");
      ser.Serialize(HttpContext.Current.Response.Output, loginResponse);
      context.Response.Write(");");

Here, loginResponse is the object we want to return to the client.

Step 4:
Now we can call from the client using the following URL
https://ServiceAddress/Service1.svc/Login?usrname=username&password=password&callback=?

“Callback=?” is the thing we need to make it JSONP
Bellow is a complete ajax call

$.ajax({
            url: https://ServiceAddress/Service1.svc/Login?usrname={username}&amp;password={password}&amp;callback=?,
            type: "GET",
            async: true,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {},
            timeout: 10000,
            success: function (loginData) {
                    return;
                }

                var loginResponseFromServer = loginData;
                localStorage.setItem('LoginResponse', JSON.stringify(loginData));
            },
            error: function (xhr, settings, exception) {                
            }
        });

Some related links you can visit to learn more:

http://learn.iis.net/page.aspx/144/how-to-set-up-ssl-on-iis/
http://www.digicert.com/ssl-certificate-installation-microsoft-iis-7.htm
http://weblogs.asp.net/srkirkland/archive/2008/02/20/wcf-bindings-needed-for-https.aspx
http://api.jquery.com/jQuery.ajax/
http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx
http://stackoverflow.com/questions/1012777/https-request-via-ajax-from-http-page

Categories: AJAX, WCF
  1. Kenny Wang
    May 23, 2013 at 3:46 pm

    Hi, Thanks your sharing, it’s help me.
    But I am wondering if the data return from server is secure or not? I mean the parameters and return data from server is still under protection w/ SSL?

  1. No trackbacks yet.

Leave a comment