Often as a web developer you run into situations where you want to protect specific
areas of your site from being seen by just everyone. A good way to do this is to add
password protection to your website. The first thing you need to do is create a login
page, which can look something like this:
<% Sub ShowLogin %>
<form name=form1 action=login.asp method=post>
User Name : <input type=text name=username>
Password : <input type=password name=userpwd>
<input type=hidden name=login value=true>
<input type=submit value="Login">
</form>
<% End Sub %>
The above code simply creates a form. The second input box has a type=password, what this does
is cause what the user has typed in to show up as stars (like *******). Also to note is that you
want the action of the form to be the same page. This way we do not need a second page just to
handle the checking of the password. I will talk about the hidden form element next. You will
also see why we placed the form inside a subroutine later.
Before we add the code to check to see if the user name and password are correct we need to add
some code to the top of login.asp to check to see if the form has been submitted.
Response.Expires = -1000 'Makes the browser not cache this page
Response.Buffer = True 'Buffers the content so our Response.Redirect will work
Session("UserLoggedIn") = ""
If Request.Form("login") = "true" Then
CheckLogin
Else
ShowLogin
End If
This code will go at the top of login.asp to see if the form was submitted. If it was then we
will check the login, if not then we will show the login form.
Next we will add the code for the CheckLogin subroutine to check to see if the username and
password entered are correct.
Sub CheckLogin
If LCase(Request.Form("username")) = "guest" And LCase(Request.Form("userpwd")) = "guest" Then
Session("UserLoggedIn") = "true"
Response.Redirect "protectedpage.asp"
Else
Response.Write("Login Failed.<br><br>")
ShowLogin
End If
End Sub
The above code will check to make sure they have entered the login correctly. By setting the Session
variable "UserLoggedIn" equal to "" we are basically logging the user out. The only thing
left to do is write the code to put at the top of the protected page to check to see if the user
is logged in.
Response.Expires = -1000 'Makes the browser not cache this page
Response.Buffer = True 'Buffers the content so our Response.Redirect will work
If Session("UserLoggedIn") <> "true" Then
Response.Redirect("login.asp")
End If
Read Part 2
where we add error messages, the ability to logout/relogin, and database checking.