Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

Creating a login script with ASP part II

Rated 3.83 (Ratings: 4) (Add your rating)

Log in to add a comment
(8 comments so far)

Want more?

  • More articles in Code
  • More articles by Neil
 
Picture of Neil

Neil McGill

Member info | Full bio

User since: May 30, 2002

Last login: May 30, 2002

Articles written: 2

In part I, we created a simple password protection for a single user to protect part of a website. Now, we will explore how to add error messages, allow users to logout/re-login, and query a database for the user name and password entered.

Updating the current script

First of all, we are building on the code already produced in part I. Find the code in the login.asp from part I shown below:

login.asp

If Request.Form("login") = "true" Then
    CheckLogin
Else
    ShowLogin
End If

And replace it with:

login = Request.Form("login")
If login = "logout" Then
    Session("UserLoggedIn") = ""
    ShowLogin
Else
    If Session("UserLoggedIn") = "true" Then
        AlreadyLoggedIn
    Else 
        If login = "true" Then
            CheckLogin
        Else
            ShowLogin
        End If
    End If
End If

Next we will add the subroutine AlreadyLoggedIn to tell the user they are logged in and ask if they want to logout/login again.

<%
Sub AlreadyLoggedIn
%>
You are already logged in.
Do you want to logout or login as a different user?
<form name=form2 action=login.asp method=post>
<input type=submit name=button1 value="Yes">
<input type=hidden name=login value="logout">
</form>
<%
End Sub
%>

Error Checking

Now to add error checking we need to declare a global error message variable, add code to format the error message and print out the message if needed.

Declare the variable to hold the error message near the top of the login page.

Dim Error_Msg

And we add this little bit of code to the beginning of the login form. This will print out an error message if there is one.

Response.Write(Error_Msg &amp; &quot;&lt;br&gt;&quot;)

What about other users?

Well, now all that is left to do add the code that checks the user name and password against a database. In order to do this we will rewrite the CheckLogin subroutine from Part I.

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

will now look like this: (assuming you use an Access Database - change the connections if different)

Sub CheckLogin
Dim Conn, cStr, sql, RS, username, userpwd
username = Request.Form("username")
userpwd = Request.Form("userpwd")
Set Conn = Server.CreateObject("ADODB.Connection")
cStr = "DRIVER={Microsoft Access Driver (*.mdb)};"
cStr = cStr & "DBQ=" & Server.MapPath("\path\to\database.mdb") & ";"
Conn.Open(cStr)
sql = "select username from UserTable where username = '" & LCase(username) & "'"
sql = sql & " and userpwd = '" & LCase(userpwd) & "'"
Set RS = Conn.Execute(sql)
If RS.BOF And RS.EOF Then
    Error_Msg = "Login Failed. Try Again."
    ShowLogin
Else
    Session("UserLoggedIn") = "true"
    Response.Redirect "protectedpage.asp"
End If
End Sub

We also need to take out the line of code that sets the Session variable equal to "". What this did was logout our user anytime they pulled up the login page. The code is:

Session(&quot;UserLoggedIn&quot;) = &quot;&quot;

And that's it. Your pages are now protected and multiple users can access them.

The Scripts in full

login.asp

<%
Response.Expires = -1000 'Makes the browser not cache this page
Response.Buffer = True 'Buffers the content so our Response.Redirect will work

Dim Error_Msg

login = Request.Form("login")
If login = "logout" Then
    Session("UserLoggedIn") = ""
    ShowLogin
Else
    If Session("UserLoggedIn") = "true" Then
        AlreadyLoggedIn
    Else 
        If login = "true" Then
            CheckLogin
        Else
            ShowLogin
        End If
    End If
End If

Sub ShowLogin
Response.Write(Error_Msg & "<br>")
%>
<form name=form1 action=login.asp method=post>
User Name : <input type=text name=username><br>
Password : <input type=password name=userpwd><br>
<input type=hidden name=login value=true>
<input type=submit value="Login">
</form>
>%
End Sub

Sub AlreadyLoggedIn
%>
You are already logged in.
Do you want to logout or login as a different user?
<form name=form2 action=login.asp method=post>
<input type=submit name=button1 value="Yes">
<input type=hidden name=login value="logout">
</form>
<%
End Sub

Sub CheckLogin
Dim Conn, cStr, sql, RS, username, userpwd
username = Request.Form("username")
userpwd = Request.Form("userpwd")
Set Conn = Server.CreateObject("ADODB.Connection")
cStr = "DRIVER={Microsoft Access Driver (*.mdb)};"
cStr = cStr & "DBQ=" & Server.MapPath("\path\to\database.mdb") & ";"
Conn.Open(cStr)
sql = "select username from UserTable where username = '" & LCase(username) & "'"
sql = sql & " and userpwd = '" & LCase(userpwd) & "'"
Set RS = Conn.Execute(sql)
If RS.BOF And RS.EOF Then
    Error_Msg = "Login Failed. Try Again."
    ShowLogin
Else
    Session("UserLoggedIn") = "true"
    Response.Redirect "protectedpage.asp"
End If
End Sub
%>

protectedpage.asp

<%
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
%>

This page is full of password protected content.  If you are reading this you entered <br>
the correct name and password.

When not abusing his workplace's blisteringly fast internet connection to play time wasting games and being a lazy so and so, Neil tries to be a Web Developer for the University where he studies Computing.

Malicious input

Submitted by Spyder on June 1, 2002 - 06:12.

I haven't tested your code for this but at work where I often have to use ASP, we had some problems with a couple our login scripts because a user could enter in an apostrophe (') as their username and password and when that was used in the SQL query, it caused a script error because the apostrophe marked a false end to the WHERE statement... It is a bit complicated but ASP would then reveal part of the SQL statement and the user could try again and add their own code to the SQL query so that it would always succeed. It is unlikely to happen but some people will try stuff like that so I guess my big lesson with that was always filter/validate user input in cases like this. Or even better, use PHP! :-D

login or register to post comments

SQL injection vulnerablility

Submitted by lonk on June 1, 2002 - 10:16.

I would agree with Spyder's comment in that the lack of validation leaves this basic script wide open to an SQL injection attack! At the very least, one should replace single quotes with double single quotes:

username = Request.Form("username")
username = Replace(username,"'","''")
userpwd = Request.Form("userpwd")
username = Replace(userpwd,"'","''")

to circumvent the most common injection method. Further, it might also be advisable to replace any semi-colons found in the input. I think it's worth investigating this type of vulnerability anytime user input is used against a database.

login or register to post comments

validation

Submitted by Nautilus on June 2, 2002 - 18:19.

thanks for the input guys. I did think of adding validation techniques to cope with malicious code, but this article (along with the first part) is supposed to be just a simple introduction into protecting your pages with logins, and to cover every hack would take a fair bit of explaining. To cover injection attacks would probably require a whole other article just to explain what they are capable of, and how to catch them.

login or register to post comments

whoops..

Submitted by Neil on June 2, 2002 - 18:37.

i was logged on with another username when i posted the above comment. Yes, it really was me, and not someone trying to take credit for the article. I really should have that user deleted now i don't use it anymore (or at least update my login cookie for evolt).

Anyway, after looking around i found a good article on SQL injection attacks on devarticles.com

login or register to post comments

more on injection

Submitted by bobince on June 4, 2002 - 18:23.

If you're escaping quotes there's no need to escape semicolons. Okay, there's little chance of a name having a semicolon in, but you might as well write a single SQL-string-literal-escaping function in your global.asa and get it right for all cases there.

There is another kind of escaping problem if you are using MDB files as your database and you haven't upgraded to a recent version of Jet. Jet will allow pipe characters in string literals which may contain VB scripting. This means an attacker can execute any system command on your server! There is a solution involving replacing '|' with a VB chr() expression, but it's nasty. Best to upgrade, or simply don't use MDBs. Access/Jet is a desktop DB app, and is simply not suited to webapp backends.

Finally, users of MySQL and PostgreSQL should be aware that there is by default another problematic character that needs to be escaped, the backslash. It should be changed in literals to a double-backslash. Otherwise an attacker can use a backslash followed by a quote to get out of a literal.

this article is supposed to be just a simple introduction into protecting your pages

That is exactly the problem with every one of these sort of tutorials I have seen. They always treat security as an afterthought if it is mentioned at all, and the upshot is everyone who learns from them goes off writing completely insecure code.

The related traits of quality and security are vital to development in an untrusted environment like the internet. It is time our learning materials taught them from the start.

login or register to post comments

Login status check through a database.

Submitted by lmittal on August 13, 2002 - 20:59.

Hello, I want to discuss a problem. I am making the user fill up a form before he want to log on. Then I make his account enable after verifying the company details about the user. This (enable process) is done through a seperate asp. But, till then the user is not allowed to log in. I am using a Flag variable which checks the login status of that user. If the Flag is 1 then the user is allowed to login otherwise if the Flag is 0 he is not allowed to login. I am facing a problem in this. How can i check for the login status (Flag) of the user while he is logging in, as he is not providing me with the login status on his own. This I have to check through a database which is in Access 97. The record contains a single entry for that user with Flag indicating the Login Status of that user. Do reply soon, if you have the answer. Thanks in advance. Email Id :- lmittal@cdotd.ernet.in

login or register to post comments

passsing the value of the user pass to unique page

Submitted by jasent on September 2, 2002 - 08:34.

In the example we have been workin with, the authenticated user is sent to a generic "members" page. I want to take the authenticated user and forward them to a page where they can view and modify their record in the MS ACCESS database. I cannot seem to get the authenticated user pass to forward correctly to aditional ASP code that will allow them to view or modify their record. I keep getting an object error when trying to re read the variables after they were authenticated. Could someone please help me with some code examples that would append to this articles code? Thank you :)

login or register to post comments

Cant get the script to work

Submitted by Phil4284 on May 4, 2006 - 12:41.

I have copied and pasted the above script and changed the database connection string and sql statement to suit my webpage but the code doesnt same to work for me, when i enter a username and password the page just redirects to the login page and clears the values entered. The error message doesnt work either, when i enter an incorrect username and password it does exactly the same, redirects to the login page and clears the values entered, can anyone help me sort this out? Thanks

login or register to post comments

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.