JavaScript: Password Protection

Posted March 11, 2006 by William_Wilson in Computer programming

If you need to password protect a webpage with javascript, continue reading to find out how this is done. (The password is not viewable in the source of the page.)

If someone really knows what they are doing, it is impossible to prevent all access with javascript, but here is a way to keep hackers from seeing your password in the source of your protected page.

To fully take advantage of this feature, you will need Unix/Linux permission knowledge or a program such as cuteFTP to change the attributes of your script file.

*Scripts are not allowed on this site, so replace * with < and replace $ with > inside the code blocks.

First, we need a page to display the password prompt. Using a simple form and action to call our eventual script is all that is necessary.
*This can be expanded to include usernames, etc.

*script src="scripts/pass.js" type="text/javascript"$*/script$
*body onLoad="top.window.focus()" BACKGROUND="images/code.jpg"$
*h1$Restricted Area: Site Admin Only*/h1$
*form name="protected"$
*input type="password" name="passw" value="" size=30$
*input type="button" name="accept" Value="Enter" onClick=checkPass(this.form)$

The line *script src=”pass.js” type=”text/javascript”$*/script$ in the head delegates the name of the script and its location.

By making the text field of type password, the text will be displayed as * instead of letters. Thus, programs which do auto-fill or auto complete will not keep their value.

Now, we have called a script function called checkPass with the button press of this form, and here is the script:

function checkPass() {

When checkPass is called, it simply checks if the password is the same as the value you wish it to be. In this case, the password is tr. Passwords are case sensitive so be careful.

**NOT all OS support this**
This is the important part. On your server/domain, you will need to modify the rights of this script such that global and group have no privileges (e.g., rw——-). They should not be allowed to read, write or execute this file.
**Windows XP definitely does not support this. You will not be able to protect your script files and have XP users execute the scripts in this manner!

Now, simply make your link to a protected file link to the html page listed here and have the if location point to the protected page. There are still ways around it, but it will take more work than simply reading your source file.

Questions/Comments: [email protected]
-William. ยง (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.