Monday, December 22, 2008

Protect Javascript

Sometimes you may have proprietary functions/algorithms that you don't want copied as they are a core object to what you're offering on your Web site (i.e. Users have payed a subscription fee to use custom-made algorithms). You want to prevent people from saving the Web site to their hard drive and simply using the functions there. Granted, you could protect the function in the code behind, or on a postback in the ASP/PHP programming, but sometimes the speed of client-side scripting is a determining factor. The downside is anyone can view the JavaScript (even if it's referenced in an external .js file). Here's a simple trick:

Note: This trick was originally done in the PHP environment; the concept should translate into the .NET world:

In your main .html, .php, .asp page, point to a file that will contain your javascript code. The file extension should be .php or .asp (whichever environment you're in):
<script language="javascript" type="text/javascript" src="/protectedJavascript.php"></script>

In the "protectedJavascript.php" file, place the following code:

if(!eregi("/originatingPage.html",$_SERVER['HTTP_REFERER'])) {
   echo "Message to those snooping here.";
} else {
   echo "//JAVASCRIPT CODE HERE";
}

Where "/originatingPage.html" is the path of which calls this protected page. In the PHP world. the !eregi() function simply looks for a match between the two strings passed in.

Anyone trying to access this page will be shown the "Message to those snooping here." text (or whatever you have placed here.) because their HTTP_REFERER will not (or ever) be "/originatingPage.html". The only way they could see just the code is if you had a hyperlink pointing directly to "protectedJavascript.php" from "/originatingPage.html."

You can obtain this same functionality with an .asp page.

No comments: