Password Protect Your Website

Javascript Tutorials

Tutorial

Click on thumbnailed images to enlarge

The techniques described below mainly apply to those users, who have a web site with a host that does not provide any possibility to execute server-site code, such as CGI or any sort of web application code, but who want to provide some control over who can access and use their web site.

When you are not able to run any code on the server, you have no choice left but to run it on the client site, or Javascript.

Even though it is possible to provide some basic protection mechanisms through Javascript, it is far from ideal, but it may be able to discourage at least some unwanted people from trying to access your web site.

The code examples below will show you how you can build a web site that you can access only after you enter a valid password at the logon page. Only then, the user will be allowed to browse your web site. You could use this technique also to restrict only certain pages on your web site, rather than the whole web site.

The first screen, index.html, will be the logon page. Basically shows nothing but a simple 'please enter your password' message and a textbox where you can enter the password.

If the right password is entered, the user will be forwarded to the first, default, web page on your site. If the password is wrong, (s)he will be presented with a red screen telling them that their access is denied.

There are 3 conditions for a user to allow access to your web site:
1) browser must allow cookies (see function isCookiesEnabled())
2) user must have visited the logon page (see functions newSession() and checkSession())
3) user must have provided a valid password (see functions passwordValidated() and checkValidation())

To keep track of those conditions, we will use cookies. The first cookie ('visitedloginscreen') will be set to 'yes' only when the index.html page was visited (see function 'startSession()' in the code example).

The second cookie ('passwordisvalid') will be set to 'yes' only after a valid password has been entered. Every other screen on your web site that requires logon, will have to check is this cookie is set. If not, forward immediately to a page illegalaccess.html, which basically tells the user (s)he does not have access to this page. This also prevents users from bookmarking this certain page. The only way to get there is through the logon screen.

Now comes the fun part: validating the password. You don't want to hard-code your password in the Javascript, because the user can easily find that by checking the browser cache. Ideally, the password is stored on the server site... and there is a way of doing this!

Basically the password is the name of an image (i.e. a 1 pixel gif file) and a forwarding page.
Let's say the password is 'secretpassword123'. We would need a file called secretpassword123.gif and a file called secretpassword123.html (this is the forwarding page).

When you enter the password on the logon page, the page will try to load the image of the same name as the password entered, plus the extension '.gif'. If this fails, password is wrong. Otherwise the password is valid and the page with the password name plus '.html' will be loaded. This 'forwarding' page merely forwards the user again to the first actual web page.

In order to detect whether the image can be loaded or not, we create an Image object in Javascript. We point the src attribute to the image, and point the onerror and the onload events to our own functions.

If the onerror event is fired, the image failed to load and we display refuse access. If the onload even is fired, we open up the forwarding page.

The forwarding page then forwards again to the first web page. The first thing that each actual web page does, is checking whether the user has visited the logon page, and whether the password was valid. This information is stored in cookies, so if the right cookies are set, we're good to go. Otherwise we will forward immediately to
the 'illegalaccess.html' page.

In order to add a bit more security to your web pages, you can give them some more cryptic file names, such as zv45x2wy_home_gv8.html instead of home.html. This makes it harder for someone to just guess some file names.

And if you want to change the password, all you have to do is rename the files secretpassword123.gif and secretpassword123.html.

In addition to all of this, you can disable the right-click event by adding the next line at the top of each page:

document.oncontextmenu = new Function("return false");

This way, the user can't view the source from the context menu, however, the source can be viewed anyways through the browser menu or by checking the browser cache. There's only so much you can do with Javascript.

The logon page (index.html):

<html>
<head>
<title>Login</title>
<script type="text/javascript">
// Disable context menu (right click)
document.oncontextmenu = new Function("return false");
</script>
<script type="text/javascript" src="session.js"></script>
<script type="text/javascript">
var passwd = "";

// This function is called when the image cannot be
// successfully loaded
function errorHandler (evt) {
alert("You have entered an invalid password.");
}

function loadHandler (evt) {
top.location.href = passwd + ".html";
}

function logon(passw) {
passwd = passw.value;
var img = new Image();
img.onload = loadHandler;
img.onerror = errorHandler;
img.src = passwd + ".gif";

passw.value="";

return false;
}

function startSession() {
if (isCookiesEnabled() == 0) {
newSession();
} else {
top.document.location.href="enablecookies.html";
}
}
</script>
</head>
<body onload="startSession();">
<form onsubmit="logon(pwd);">
<p>Please enter your password:<br/>
<input type="password" id="pwd" name="pwd"/><br/></p>
</form>
<noscript>
<p>Your browser does not support, or is not enabled to run Javascript.</p>
</noscript>
</body>
</html>


javascript file (session.js):

// Set a cookie
function setCookie(name, value, expires, path, domain, secure) {
// set time, it's in milliseconds
var today = new Date();
today.setTime(today.getTime());

if (expires) {
expires = expires * 1000 * 60;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + "=" + escape(value) +
((expires) ? ";expires=" + expires_date.toGMTString() : "") +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
((secure) ? ";secure" : "");
}

// Get the specified cookie
function getCookie(name) {

var dc = document.cookie;
var start = dc.indexOf(name + "=");
var len = start + name.length + 1;

if ((!start) &&
(name != dc.substring(0, name.length))) {
return null;
}

if (start == -1) return null;
var end = dc.indexOf( ";", len );
if (end == -1) end = dc.length;
return unescape(dc.substring(len, end));
}

// Indicate that user visited the logon page.
function newSession() {
setCookie("visitedloginscreen", "yes", "", "/", "", "");
}

// Indicate that the password entered is valid.
function passwordValidated() {
setCookie("passwordisvalid", "yes", "", "/", "", "");
}

// Check whether user visited logon page.
function checkSession() {
if (getCookie("visitedloginscreen") != "yes") {
top.location.href="illegalaccess.html";
}
}

// Check whether user entered valid password.
function checkValidation() {
if (getCookie("passwordisvalid") != "yes") {
top.location.href="illegalaccess.html";
}
}

// Check if cookies are enabled on client browser.
function isCookiesEnabled() {
setCookie("cookiesenabled", "yes", "", "/", "", "");
if (getCookie("cookiesenabled") != "yes") {
return -1;
} else {
return 0;
}
}


error screen (illegalaccess.html):

<html>
<head>
<title>Illegal Access</title>
</head>
<body style="background: red;">
<h1><br/><br/>ACCESS DENIED!!</h1>
</body>
</html>


error screen (enablecookies.html):

<html>
<head>
<title>Enable Cookies</title>
</head>
<body style="background: green;">
<h3>You need to enable cookies on your browser.</h3>
</body>
</html>



forwarding page (secretpassword123.html):

<html>
<head>
<title>Login</title>
<script type="text/javascript" src="session.js"></script>
<script type="text/javascript">
checkSession();
passwordValidated();
window.top.location.href="zv45x2wy_home_gv8.html";
</script>
</head>
<body>
<p>ILLEGAL ACCESS!!</p>
</body>
</html>


First actual web page (zv45x2wy_home_gv8.html)

<html>
<head>
<title>Welcome!</title>
<script type="text/javascript">
document.oncontextmenu = new Function("return false");
checkSession();
checkValidation();
</script>
</head>
<body>
<p>Welcome to my home page!</p>
</body>
</html>


Tutorial also available at this [link].

Tutorial Comments

Showing latest 1 of 1 comments

Thanks for the help!

By taddred on Dec 22, 2009 3:59 am

Tutorial Details

Author kaerts View profile
Submitted on Feb 11, 2006
Page views 18,551
Favorites 6
Comments 1