.Net, ASP.NET, C#, HTML, JavaScript, Programming, VB.NET, Web Development, WebForms

Simplest Way to Pass Cross Domain Values to your JavaScript

If you are writing code for one site and want to get data from another, you face a limited set of options for how to do so. This is especially true if you want to get information for your client side JavaScript from server-side code from a server on another domain.

Let’s Imagine the Following Example Scenario:

For starters, lets say that you are coding for a site that only supports HTML and client-side JavaScript, but you want to check user credentials of your visitors using Windows Integrated Authentication. You cannot easily do so without altering IIS settings or your Web.config file, but doing so is not possible in this example scenario. You will need to find a code-only solution to this problem.

More specifically, the basic restrictions/challenges that we are going to impose in this example that restrict what solutions we can use are:

  1. We can apply code changes to two domains, but we cannot in any way change the web.config files or the IIS settings.
  2. Furthermore, we are writing JavaScript code for a site that does not support server-side code, but we want to check for Windows Authentication user credentials which is only possible from the server-side.
  3. The authentication cannot be done on the server hosting the JavaScript page… it is only available on a remote domain where. The remote server does allow server-side code in the form of ASP.NET Web pages.
  4. Bottom line is that we want the identity of the page visitor to be available to our JavaScript code.

Deciding what Solution to Use

Since we cannot change any Web server settings and the server hosting our client-facing code only supports HTML/JavaScript, we will need to query our second server (which does support Windows Authentication) for the identity of the visiting users.

There are a number of ways that you could use to try to communicate cross domain with your ASP.NET code. You could call an ASP.NET web service via an AJAX request if your receiving server is properly set up. Likewise you could set up a JSONP call via JQuery to a file on your ASP.NET enabled Web server.

These options are all quite involved and can easily frustrate you with the code related security settings that need to be configured in order for the cross domain/cross server communication to work.

The key in looking into this issue is to realize that your browser tries to sandbox most things that you do to discourage cross domain communication. However, your browser does allow files such as images, CSS include files, and JavaScript include files to be referenced across different servers and domains.

This leads us to understand that the most straightforward way to communicate cross domain is to simply include dynamically generated JavaScript from your remote domain as a JavaScript library.

How Does it Work?

For starters you’ll need to write the ASP.NET object on your remote server:

  1. First set the return mime type for your ASP.NET page to application/javascript.
  2. This will make sure that a .js response will be returned to your calling page.
  3. When the ASP.NET page is loaded remotely, in order for the page to render, the user will be authenticated using Windows Authentication on the remote server.
  4. This means that you can get the user’s ID in the standard way using: HttpContext.Current.User.Identity.Name;
  5. To get all of this information back you will need to encapsulate the data that you want to return in a JavaScript function. You can do so by concatenating together the JavaScript as a String object

Once you have put together your code, you can stream the response as a JavaScript library by setting the response content MIME type to be application/JavaScript.

Below I’m giving an example of the code-behind ASP.NET page in both C# and VB.NET that authenticates users and returns the result as a JavaScript function. After that, I’ve included an example page from the client-facing domain that references ASP.NET JavaScript across domains and alerts the result when the page first loads.

An ASP.NET Web Page Written in C# Called MyScriptPageCSharp.aspx

Here is an example page written in C# that illustrates the concept of doing server-side Windows authentication and then passing the results in a JavaScript function as a JavaScript library.

<%@ Page Language="C#" %>
<script runat="server">
 protected void Page_Load(object sender, System.EventArgs e)
 {
 string strMyUserIdent = HttpContext.Current.User.Identity.Name;
 if (strMyUserIdent.Contains("\\"))
 {
 strMyUserIdent = strMyUserIdent.Remove(0, strMyUserIdent.IndexOf("\\") + 1);
 }
 strMyUserIdent = strMyUserIdent.Replace("'", "''");
 string strOut = " function myUserId(){" + Environment.NewLine;
 strOut += " return '" + strMyUserIdent + "'; " + Environment.NewLine;
 strOut += "} " + Environment.NewLine;
 Response.Clear();
 Response.ContentType = "application/javascript";
 Response.Write(strOut);
 Response.End();
 }
</script>

The Same ASP.NET Web Page, but Written in VB.NET: Called MyScriptPageVB.aspx

Here is the same example as above, but written in VB.NET

<%@ Page Language="VB" %>
<script runat="server">
 Protected Sub Page_Load(sender As Object, e As System.EventArgs)
 Dim strMyUserIdent As String = HttpContext.Current.User.Identity.Name
 If strMyUserIdent.Contains("\") Then
 strMyUserIdent = strMyUserIdent.Remove(0, strMyUserIdent.IndexOf("\") + 1)
 End If
 strMyUserIdent = strMyUserIdent.Replace("'", "''")
 Dim strOut As String = " function myUserId(){" & Environment.NewLine()
 strOut &= " return '" & strMyUserIdent & "'; " & Environment.NewLine()
 strOut &= "} " & Environment.NewLine()
 Response.Clear()
 Response.ContentType = "application/javascript"
 Response.Write(strOut)
 Response.End()
 End Sub
</script>

Example JavaScript/HTML Page that gets the JavaScript Generated by the Remote ASP.NET

Below is an HTML/JavaScript Web Page that includes the script output of MyScriptPageCSharp.aspx shown above. Notice that the inclusion of the ASP.NET generated JavaScript library is cross server/cross domain.

After the JavaScript library is referenced, a page-level JavaScript is called in the HTML body load event. The page-level function does an alerts of the return value from the cross-domain function that was dynamically constructed in either of our ASP.NET examples above.

<html>
<head>
 <title></title>
<script src="http://example.com /MyScriptPageCSharp.aspx" type="text/javascript"></script>
<script type="text/javascript">
 function checkUser() {
 alert('hi ' + myUserId());
 }
</script>
</head>
<body onload="checkUser();">
</body>
</html>

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s