Quick Tip: Lock Your SWF to a Specific Domain Name

Quick Tip: Lock Your SWF to a Specific Domain Name

Tutorial Details
  • Difficulty: Intermediate
  • Program: Flash
  • Estimated Completion Time: 20 mins

Do you want to keep your SWF exclusive to your site? In this Quick Tip, we’ll look at how to use a “site lock” to stop people downloading your SWF and embedding it on a different website.


Final Result Preview

Here is the file running on an incorrect domain:

We’ll build an animated display to be activated when the SWF is on the wrong domain, as in the above example. Saying that, if you just want to learn about the site lock code, skip to Step 5.


Step 1: Tweener

Before you get started writing code and adding designs to the stage, you must first get Tweener. For this project I used open source, which can be used for open and commercial projects. Caurina tweener is available a code.google.com.

After you have downloaded Tweener, just copy and paste it to your project folder. Remember, the folder must be named caurina, inside the folder there must be a folder called transitions, and inside of that a load of Flash .as class files.

With the first step done, we can get on with coding and designing the file.


Step 2: File Size and Layers

The file size is irrelevant. Domain locker’s property is to lockdown your SWF, or component, in case someone has downloaded it from you without your permission.

For this example, I have used a stage size of 540 x 400, you can use whatever size you want.

After you’ve selected the file size, create 3 new layers as in the image below. Always keep your Actions Layer empty. Organised stages are much easier to work with and understand.


Step 3: The Censor System

After you have created the 3 layers, create 2 new simple movieclips. Place them wherever you want, whatever size you want. 40 pixel height by 10 pixel width let’s say, with no stroke. Positioning is not important, because we will be placing these movieclips by actionscript later on.

Now, comes the most important aspect of these movieclips, the registration point. Look at the pictures below, when converting your bitmaps to movieclips, remember to do the following else the file will not run at it’s full potential:

And of course, the instance names:

 

Congratulations! You’ve added the boxes that will shut the page down, in case the domain is wrong. Now, add a dynamic text box to the middle of the stage or anywhere you want it to be. This text box will inform the user who downloaded the file illegally that the file is protected by the script.. Give it an instance name of warning_txt


Step 4: Loading Necessary Classes

Now, once you’ve created the movieclips and the text box, you are ready to code. On the locked actions layer, press F9, and add the following code:

import flash.events.*;
import flash.display.LoaderInfo;
import flash.display.MovieClip;
import flash.net.navigateToURL;
import flash.net.URLRequest;
import flash.net.URLVariables;
import caurina.transitions.Tweener
  • flash.events.*; loads all the events we will probably need.
  • flash.display.LoaderInfo; brings up all information we need to load and that will load with the file.
  • flash.flash.display.MovieClip; loads all the events we will come across while using movieclips.
  • import caurina.transitions.Tweener; loads our tween engine, and the animation of the content blocking bars.

The rest of the events loaded are needed so that Flash gets access to the page URL in the bar.


Step 5: Checking for a Specific Page

var url:String = stage.loaderInfo.url;

Let’s suppose the SWF is loaded on the page http://www.domainName.com/siteFolder/sitePage.html. Line 9 retrieves this URL and assigns it to the string called url.


Step 6: Cause and Effect

Now that Flash knows where to get the URL from, it’s time to compare that with our web site’s URL, and take action if they match or don’t

function pageDomainCheckInit(event:Event):void {
	if (url != "http://www.domainName.com/siteFolder/sitePage.html") {
    
		warning_txt.text="This file is running on the wrong URL. Content Access Restricted!";
		closeBoxTop.x = 0
		closeBoxTop.visible = true;
		closeBoxTop.height= stage.stageHeight/2
		Tweener.addTween(closeBoxTop,{width:stage.stageWidth, alpha: 0.8, time:1, transition:"easeInOutExpo"});

		closeBoxBottom.x = stage.stageWidth
		closeBoxBottom.visible = true;
		closeBoxBottom.height= stage.stageHeight/2
		Tweener.addTween(closeBoxBottom,{width:stage.stageWidth, time:1, alpha: 0.8, transition:"easeInOutExpo"});
	} else {
    
		warning_txt.text=" ";
		closeBoxTop.visible = false;
		closeBoxBottom.visible = false;
	}
	stage.removeEventListener(Event.ENTER_FRAME, pageDomainCheckInit);
}

stage.addEventListener(Event.ENTER_FRAME, pageDomainCheckInit);

We’ve used an event listener to start the check-up of the previously detected URL string. What this basically does, is tell flash that if the string located in the navigation bar (or the URL where the page is hosted on) is not the correct one, then the page will execute the script of blocking out content and warn the user that the domain is incorrect. Otherwise, if the page is correctly placed, the boxes that close up the page will not be shown, neither will the warning text.

After this section is completed, we remove the event listener so the file does not eat up resources by checking and rechecking and rechecking over and over again. Once the string is successfully pulled, compared, and the script is successfully executed, the pageDomainCheckInit event is removed.

if (url != "http://www.domainName.com/siteFolder/sitePage.html") {

This section of the code, is basically an “IF NOT”, so if the page is not http://www.domainName.com/siteFolder/sitePage.html Flash will start executing functions below the IF, but otherwise – if the SWF is on the correct page – Flash will remove the blocks from stage, and keep everything neat and tidy. You’ll never know it’s there.

Now, let’s see what happens, when the file is not on the right domain.

warning_txt.text="This file is running on the wrong pageDomain. Content Access Restricted!";
closeBoxTop.x = 0
closeBoxTop.visible = true;
closeBoxTop.height= stage.stageHeight/2
Tweener.addTween(closeBoxTop,{width:stage.stageWidth, alpha: 0.8, time:1, transition:"easeInOutExpo"});

closeBoxBottom.x = stage.stageWidth
closeBoxBottom.visible = true;
closeBoxBottom.height= stage.stageHeight/2
Tweener.addTween(closeBoxBottom,{width:stage.stageWidth, time:1, alpha: 0.8, transition:"easeInOutExpo"});

The code you see here, positions the closeBoxes to stage start and stage end (closeBoxTop = 0 , closeBoxBotton = stage.stageWidth), and makes them invisible (closeBoxTop.visible = false, closeBoxBottom.visible = false) this hides them from the stage, keeps them away from view, and does not affect the site’s appearance. Nevertheless, they are there.

If the page, or the component is installed on a different site/domain name which it was not originally intended to be on, they become visible. They expand across the screen, covering it completely and alerting the user that the content is stolen or not where it’s supposed to be.

This measure not only informs the general user that the file is not where it’s supposed to be, but it also blocks out any content from being displayed.


Step 7: Checking for a Specific Domain

What if we only want to check whether the SWF is loaded on a specific domain?

So instead of checking if the SWF is at http://www.domainName.com/siteFolder/sitePage.html, we just check if it’s somewhere on the domainName.com website. So it could be at https://private.domainName.com/secure/secret.html and still work.

We can achieve this by editing the code that gets the URL, like so:

var url:String = stage.loaderInfo.url;		//this line was here before!
var urlBeginning:int = url.indexOf("://") + 3;
var urlTermination:int = url.indexOf("/", urlBeginning);
var pageDomain:String = url.substring(urlBeginning, urlTermination);
var lastDot:int = pageDomain.lastIndexOf(".") - 1;
var CharacterAfterDomain:int = pageDomain.lastIndexOf(".", lastDot) + 1;
pageDomain = pageDomain.substring(CharacterAfterDomain, pageDomain.length);

Code explained

Let’s suppose the SWF is loaded on the page http://www.domainName.com/siteFolder/sitePage.html. Line 9 retrieves this URL and assigns it to the String called url. That’s the same line we had before.

Line 10 of code retrieves the position within the URL of the ://

Line 11 of code retrieves the first / that appears in the URL after the ://. This is actually very important because between these your actual domain name can be found.

Line 12 of code, is just making the connection inside Flash of what’s in between the :// and the first / getting the domain name String ready for checking in the next step. At this point, with our example, pageDomain has been set to www.domainName.com.

The remaining code checks for the domain name string, what is before it (meaning “www” or “http://www.”) and what is after your domain name (meaning the “.”).

All of these are ignored, so that Flash can define the actual domain name. The domainName.com. Instead of checking:

if (url != "http://www.domainName.com/siteFolder/sitePage.html") {

…we check:

if (pageDomain != "domainName.com") {

The main problem with this technique is that it doesn’t work for domains that have three parts. For example, domainName.co.uk – this code will get “.co.uk” as the value of pageDomain. Still, it is my preferred method, as I will explain in the next step.


Step 8: Utility?

You may have several files on your server, on different domains, this method could have been done in such a manner that the file would be locked on one single and unique URL, as above. But if you were to run your file using deep linking for example, or subdomains, the file would stop working, due to the fact that the link would be invalid to the domain reader.

The fact that the code is if (pageDomain != "domainName.com") is very important. It will permit you to add this code to every file on your site, subdomain, deep link location; as long as your link is on that domain, the file will run, and the domain locker will not trigger!

Still, it can be useful to lock to something more specific than a domain name. Suppose you host your web site on a host like Amazon S3. Then your URL will be something like http://yoursitename.s3.amazonaws.com/folder/page.html. But someone else on Amazon S3 could have the URL http://someoneelse.s3.amazonaws.com/. They could upload the SWF to their site, and since the SWF would still be on amazonaws.com the domain locker would not lock.

Tip

Here’s a little tip you might really love. Let’s presume for a moment that you have the same content on several domain names and you don’t want to add a different code for each of your domains. You can make the file check for multiple domains at once really easily.

Meet the AND operator: && Using this command inside the first checker you can add as many domains as you wish. Let me show you how! :)

Single domain checker:

(pageDomain!="domainName.com")

Multiple domain checker:

( (pageDomain!="domainName.com") && (pageDomain != "mydomain.com") && (pageDomain != "hisdomain.com") ) really easy, isn’t it?


Conclusion

Well, this wraps it up. As you all know, full protection of flash files is never guaranteed 100%, but this is just another step, in making your site safer, better, and more secure against file theft. Don’t forget to encrypt your files before adding them to the server! Thanks for reading this tutorial, I hope it was useful to you, if you need any further help, don’t hesitate to leave your questions within the comment section.

Enabled is Enabled on Activeden
Tags: Tips
  • http://active.tutsplus.com/author/konstantin-serov/ Konstantin

    Pretty interesting. But it will only work if someone wants to put your app on his site as is. It will not save the app from decompilers

  • http://adrianchiran.com Adrian Chiran

    Nice tip :)

  • http://www.kolnedra.com KolNedra

    You might want to add a Security.sandboxType check and maybe put all the “allowed” domain names in an array, or even use a regular expression to allow domains like *.yourdomain.com

    • http://michaeljameswilliams.com/ Michael Williams

      Good call.

  • http://www.eclipsedesign.eu Kartlos Tchavelachvili

    Good to know that it’s possible, thanks

  • vasu

    Thanks.
    (I like that lock icon :) )

  • Nikita

    Did you check the code before posting it? That multiple domain checker looks wrong to me (both the syntax and the logic).
    Basically what you try to do is:
    If the domain is not A or the domain is not B or the domain is not C then terminate.
    That doesn’t make sense as the domain must be A, B and C at the same time to fail the condition and prevent the lock.
    For instance the SWF is run from domain A. Here’s how the check goes:
    1. Is domain not equal to A? False
    2. Is domain not equal to B? True. Domain lock activated.
    Check number 3 doesn’t happen because 2 is true.

    What you want to do is:

    (pageDomain!=”domainName.com” && pageDomain!=”mydomain.com” && pageDomain!=”hisdomain.com”)

    You use AND: If all domain checks fail (domain != A AND domain != B AND domain != C) then lock the app

    To me this seems correct and the code you gave seems wrong. But feel free to correct me if I made a mistake :)

    Cheers,
    NIkita

    • http://michaeljameswilliams.com/ Michael Williams

      How embarrassing. You’re totally right, of course! I think originally it was meant to say:

      if ( !(pageDomain=="domainName.com" || pageDomain=="mydomain.com" || pageDomain=="hisdomain.com") )
      

      …and then got mixed up somehow.

      Thanks for pointing it out :)

      • http://cosmincotor.com Cosmin

        The code is actually correct, and it’s with && not || why ?

        if domain != A > do nasty stuff (for one domain)

        now for more:

        if domain != A && domain != B > do nasty stuff , if one of those conditions is false it triggers another function or moves on without doing anything. (he’s checking if it’s not equal).

        Hope this helps ;) (note: the code above is only an example not a working AS3 code)

  • http://www.flashcomponentstemplates.com LGLab

    Thanks ;-)

  • http://wessite.com/ wessite

    Thanks for this tutorial, but I’m not quite sure it’s all correct. I thought it wasn’t possible to get the page url (browser url) from within a swf (without using javascript or flashvars). loaderInfo.url holds the url of the swf file. Correct me if I’m wrong…

    • http://www.paultrifa.com Enabled
      Author

      Well, it is possible. I’ve made a script on activeden that shares your URL on social networks. It is possible both in AS2 and AS3. But, correct me if I am wrong, in order to have a Flash site installed correctly, don’t you need a HTML file and a .js file? ( In order for it to run smoothly ) Indeed, using only Flash, the value you receive from exporting the file is “null” but in a browser and using a HTML and a JS it works like a charm. It might also work just going directly to the SWF, I am not sure of that.

  • http://www.swastiksolutions.in Hiren Khambhayta

    Hey got nice trick, previously I used to load movie to the original swf to protect stealing from the browser.
    Thanks for interesting tip.

  • venkatesh

    i read your tutorial it is very useful to me. i want to encrypt swf files. i dont know how to do? i need tutorial for that.

  • http://www.google.com kim

    Hey can you give me software or its list than can directly takes many or one (*.swf) files that i created at once and asks 4 domain list and directly Locks it and GO ……….

    Please help me….

    thank you in advance> active | tut+ team <