|
Password Protection Using the JavaScript Cookie Method
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're using a
free host or a 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 to password protect
your website with JavaScript using cookies. This method should NOT be
used for anything that absolutely MUST be password protected.
Any JavaScript that you place in the head or body sections 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 a separate include
file and then 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 type="text/javascript" src="access.js"></script>
Your website's visitors can see that a JavaScript include file is defined,
and even the exact location and name of the include file, but they can't read
the code in your 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.
|