|
Password Protection Using JavaScript
By Stephen Bucaro
If you want to restrict access to your website to only members or subscribers,
how can you implement password protection? If you own the server, or if your web host
provider allows, you can use the servers built-in security features. If your Web
host provider allows you to run custom scripts, you can use a php or asp script to
implement password protection. But what if you are using a free host or pay host
that does not allow custom scripts?
You can password protect a webpage or your entire website with some very simple
JavaScript. In this article, I provide you with the code for two different methods
to password protect your website with JavaScript. The first method uses
cookies, the second method uses frames.
Any JavaScript that you place in the head or body of your webpage is visible to
the user. To learn the password, the user merely has to right click on your webpage
and select "View Source" in the popup menu that appears. That makes it very easy for
anyone to get around your password protection scheme. For this reason you must place
your JavaScript code in an include file and use an include statement
in your webpages.
JavaScript code in an "include" file is not visible to your website's visitor.
When a user tries to view your webpage source code, all they see is the include
statement like the one shown below.
<script language="JavaScript" src="access.js"></script>
They can see that a JavaScript include file is defined, and even the exact location and
name of the include file, but they can not read the code in your JavaScript include file.
To password protect your website, paste the include statement shown above into
the head section of every page on your website except for the login page. The entire
JavaScript code for the file access.js is shown below.
var strCookie = document.cookie;
var found = false;
var loc1, loc2;
var i = 0;
while(i <= strCookie.length)
{
loc1 = i;
loc2 = loc1 + 6;
if(strCookie.substring(loc1,loc2) == "access")
{
found = true;
break;
}
i++;
}
if(!found)
{
document.location = "login.htm";
}
I'm not going to bore you with the details about exactly how this code works. Basically
it searches the cookie cache on the users computer for a cookie named "access". If it
can't find a cookie named "access", it redirects the users browser to your login page.
For this example, I named the login webpage file login.htm. Using the html code
shown below, your login page displays a password text box.
<form>
Password:<input name="password" type="password">
<input type="button" value="Sumit"
onClick="validate(this.form)">
</form>
Note that the password form button's onClick event calls a function named "validate".
Again, you hide the JavaScript code for the validate function by placing it in an include file
and placing the following line in the head section of your login page.
<script language="JavaScript" src="validate.js"></script>
|