Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

Restricting Access to Your JavaScript libraries

Rated 3.18 (Ratings: 9) (Add your rating)

Log in to add a comment
(17 comments so far)

Want more?

 
Picture of georgec

George

Member info | Full bio

User since: April 21, 2003

Last login: April 21, 2003

Articles written: 2

Restricting access to JavaScript libraries to designated domains

JavaScript libraries allow us to separate script from page, so multiple pages can all utilize the same script simply by linking to it:

<script src="greatscript.js"></script>

Just to refresh our memories, "myscript.js" should contain the script itself minus the surrounding <script></script> tags, and saved as a text file (but with .js extension).

Now, the nature of JS libraries means that they're not only accessible by your site/domain, but anyone's. Like an image, a library could potentially be utilized by any site that decides they like your script but not the bandwidth associated with it. Specifically, they would simply use a syntax like the following on their page:

&lt;script src=&quot;http://www.yourdomain.com/greatscript.js&quot;&gt;&lt;/script&gt;

This can become a headache, especially if the library is very large.

Using JavaScript to restrict access to JS libraries to designated domains

First stop- using JavaScript to safe guard JavaScript! You may already know that the language is capable of determining the current URL in the location field of the browser, through the property

document.location.href//returns the URL in the location field of browser

With that in mind, all we need is a piece of code that compares this URL with a list of permitted ones, and if non of the later matches the former, we know the library is being accessed from an outside source (and take appropriate action). Suffice it to say such a code will need to be added directly inside the library in question in order to take effect.

Lets turn theory into reality. The below code will prevent unauthorized domains from referencing the containing JavaScript library:

//Beginning of "test.js" file
var accepted_domains=new Array("wsabstract.com","javascriptkit.com")

var domaincheck=document.location.href //retrieve the current URL of user browser
var accepted_ok=false //set acess to false by default

if (domaincheck.indexOf("http")!=-1){ //if this is a http request
for (r=0;r<accepted_domains.length;r++){
if (domaincheck.indexOf(accepted_domains[r])!=-1){ //if a match is found
accepted_ok=true //set access to true, and break out of loop
break
}
}
}
else
accepted_ok=true

if (!accepted_ok){
alert("You\'re not allowed to directly link to this .js file on our server!")
history.back(-1)
}

/////rest of your libray
"
"
"

We first define an array to hold a list of the "permitted" domains. Then, we enlist the JavaScript property document.location.href to get the current URL of the user's browser. Now we have both of our key witnesses in our custody- the list of permitted domains, plus the current URL (which includes domain) of the page. All that's left to do is to compare the two, and only allow the library to proceed "loading" if there is a match (if one of accepted_domain's values is contained within domaincheck). This is done using a for loop.

Notice how the code above checks to see if the document's URL contains "http" first before proceeding with the match making. The purpose of this is so that offline accessing of the JavaScript library is left out of the scrutinization process- obviously there's no point in restricting access of a library when it's accessed offline, especially if you want to be able to test the library out on your hard drive!

Using JavaScript to limit access to a library is perfectly viable, but it does have its shortcomings. Obviously you'll need to make physical changes to your library. Then there's the repetitious work involved if you ever want to apply the restriction to all JS libraries on your site. Another solution for this- if you can handle it- is via server side scripting, specifically, .htaccess. Let's look at that now.

Using .htaccess instead for the task

In the tutorial Comprehensive Guide to .htaccess, it featured a magical little file called .htaccess of your server (you may or may not have access to it, depending on your web host), and how it can enable everything from custom 404 pages, password protection of directories, to disabling hot linking of images on your server. Well, faced with our current challenge, we simply need to elaborate on that last point a bit, so instead of- or apart from- images, JavaScript libraries are included within the list of files not to be accessed from outside your site.

Take a look at the below code, which is all that's needed to accomplish the task using .htaccess:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?wsabstract.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?javascriptkit.com/.*$ [NC]
RewriteRule \.(js|gif|jpg)$ - [F]

Notice "js" in the last line, which adds .js files, along with .gif and .jpg to the type of files only the domains listed above can access. The code should be saved inside your .htaccess file, and dropped into your web page directory.

George is the webmaster of JavaScript Kit (http://www.javascriptkit.com), a comprehensive site featuring tutorials and scripts on JavaScript, DHTML, CSS, and web design. He also mantains the developer's help forum CodingForums.com.

What's to stop...

Submitted by velvetjones on July 15, 2003 - 10:01.

... someone from just downloading the scripts and running them directly from their own servers?

login or register to post comments

Re: What's to stop

Submitted by bmason on July 15, 2003 - 10:41.

Nothing. The point is not to keep the contents of the script secret (a foolhardy exercise) but to save your bandwidth. If you come to my site and copy my script for your use, you're running it off of your server, not mine.

login or register to post comments

there's always a way..

Submitted by rogerly on July 15, 2003 - 14:35.

If you put this in your HTML page it will prevent the block from happening:

<script type="text/javascript">
accepted_ok = true;
</script>

By declaring a global accepted_ok variable, it effectively overrides the variable being used in the .js file, and the allowed domain check will always return true, and allow all scripts to continue.

Also, this block doesn't actually block bandwidth usage, it just discourages the usage of the script. If a user were to include the .js file in their web page, it would still incur the bandwidth to download the entire .js file, even if it wasn't in the allowed domain list

Basically, unless you do blocking on the server level, it will be really difficult for you to block people from using your publicly available javascript libraries. If they can read your code, they can break your code.

login or register to post comments

sorry, missed the .htaccess part...

Submitted by rogerly on July 15, 2003 - 15:09.

the .htaccess changes you mentioned seem to be the best way to do the blocking. By putting the blocking code in javascript, there are probably many ways to break through it and allow use of your libraries. If you completely block the user from downloading the library, you've effectively blocked out the people you want to block.

One question about the .htaccess changes though: I know some browsers drop the referrer sometimes (and some proxies, etc.). If that's the case, do you lose out on a chunk of customers who are using your site, but for some reason outside of their control, don't pass along their referrer when they browse?

I don't know of any good alternatives, off-hand, but these are a couple of things you should keep in mind if you decide to implement some kind of javascript library blocking.

login or register to post comments

Re: sorry, missed the .htaccess part...

Submitted by happysteve on July 16, 2003 - 06:18.

The first condition in the .htaccess is to check if the referer is NOT blank. If the browser does not return a referer, then that condition fails and allows the file to go through. By the way, mod_rewrite is required for the .htaccess to work.

I'd also add one more flag to the RewriteRule:

Old: RewriteRule \.(js|gif|jpg)$ - [F]<br />
New: RewriteRule \.(js|gif|jpg)$ - [F,NC]<br />

the NC mean "No Case", so it'll apply towards GIF, Gif, Jpg, JS, etc...

login or register to post comments

comments

Submitted by georgec on July 16, 2003 - 14:14.

If your server supports mod_rewrite, obviously the best way to prevent hot linking of .js files is to use the .htaccess file. Like happysteve says, the first condition should take care of users that don't transmit referer information, so it's safe. In any event, I don't think that renders the client side technique useless, as even though it's easy to overcome, it's meant to prevent casual hot linkers that often don't know enough about JS anyway to get around things, and works for webmasters that can't manipulate the .htaccess file on their server.

login or register to post comments

Thanks!

Submitted by g1smd on July 20, 2003 - 00:10.

Nice article. Simple and to the point.

The code doesn't stop people taking a copy of your code and then running it on their server, it merely stops them referring to your copy from their pages so preventing them from pushing up your server and hosting bill whilst lowering theirs. Nice and simple.

login or register to post comments

Not going to work with proxies

Submitted by jma on July 20, 2003 - 08:04.

Some proxies remove HTTP referer header (and some browsers don't even send it). Plus it may confuse browsers caching the script. Better you don't add critical business logic to the scripts.

login or register to post comments

For IE

Submitted by hyperizer on July 21, 2003 - 07:46.

I found on my site I had to remove the trailing slash after the domain name, since IE doesn't always append it. I had to do this:

RewriteCond %{HTTP_REFERER} !^http://(www\.)?wsabstract.com.*$ [NC]

login or register to post comments

misleading

Submitted by jweissig on July 21, 2003 - 12:41.

Your article title is misleading. It should have said using javascript to save bandwidth or using mod_rewrite to save bandwidth. I hate to be a prick but if you attempt to restrict access to a javascript file you will only fool the less intelligent. There are several methods of circumventing referrer filtering and I dont think this is a viable solution. What happens if the user uses wget or perl and crafts a referrer?

login or register to post comments

Referrer is obsolete

Submitted by cache on July 23, 2003 - 08:14.

Earlier this tear Norton and ZoneAlarm firewalls began shipping with http_referer disabled by default. On sites where I keep track, up to 20% of visitors are now not sending a referrer. As far as I can see, the http_referer is dead.

login or register to post comments

dunno

Submitted by hyperizer on July 25, 2003 - 13:50.

What happens if the user uses wget or perl and crafts a referrer?

I doubt the kind of people who would link directly to your JavaScript or images are that sophisticated. From my site logs, it looks like most people stealing bandwidth are just kids posting to message boards.

login or register to post comments

What's the point?

Submitted by jim.dabell on September 17, 2003 - 02:31.

Instead of writing code to serve to clients that could potentially interfere with legitimate clients, why not just write code to check your logs for requests for your Javascript files that contain a Referer header that doesn't match your domain and isn't blank? Stick it in a cron job to run daily, and when somebody tries to nick your bandwidth, you get emailed within 24 hours. If at that point they refuse to do the decent thing, you can go ahead with blocking a specific address, which is much less likely to interfere with legitimate clients. Or you could just complain to their provider.

login or register to post comments

fake referrers

Submitted by cobra on October 7, 2003 - 03:55.

I think, it's very easy to fake the any referrers by means the simple PERL script using the LWP module

login or register to post comments

how to prevent .js from being viewd or downloaded

Submitted by crossinjl on November 17, 2004 - 17:58.

So how to prevent the *.js files from being viewed when someone types the url, for example, http://www.yoursite.com/path1/yourjavascript.js? I saw some articles that use .htaccess files with Rewrite stuff inside. If you just wanted to use Rewrite redirection inside httpd.conf file (as opposed in .htaccess), can someone give an example?

login or register to post comments

stop norton and other proxys from reading javascript files

Submitted by tom_taylor on September 3, 2006 - 13:46.

Hiya we need to stop nortons internet security and antivirus proxy's from reading .js files if possible i use php server side to restrict anyone or anything other than the web server requesting the file so the webpage can use the javascript within due to norton reading it first, it refuses to load within the webpage so no javascript will then function the javascript for client side protection example above also barfs up not tried the mod_rewrite rules as of yet, but i have a feelin they may not work, unless we can make this stronger and stop norton in its tracks first, so the webpage can carry on loading our protected javascript cheers, Tom Taylor - http://

login or register to post comments

Why not CSS as well?

Submitted by g1smd on October 30, 2007 - 13:47.

I have recently found someone hotlinking the stylesheet on one of the sites I have been updating.

Using Mod_Rewrite they now get an alternative, very short stylesheet, where every element is set to either display:none or the text is blown up so that one word almost fills the whole screen.

Let's see how long it takes for the hotlink to disappear. It's been three days already, and it is still there.

Interestingly, none of their visitors go to any other pages of the site once they arrive at any page of the site. They can't. They are looking at a blank page or a page with a few words of HUGE text and no navigation.

I can see that from the log files, here.

login or register to post comments

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.