When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
Related Web Technologies
User Tips!
Coding Tips

Sample Chapters
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Stump the SQL Guru!
XML Info
Author an Article

The 4 Guys Present: ASPFAQs.com

Jump to a FAQ
Enter FAQ #:
..or see our 10 Most Viewed FAQs.

4GuysFromRolla.com : ASP FAQS : Security


How can I restrict access to a page or a portion of my Web site?

[Print this FAQ]

Answer: FAQ submitted by Doug Down (Doug D)

When I first started creating ASP Web sites I quickly found that on some sites I needed to be able to "protect" certain Web pages; that is, I needed to have certain Web pages that were only viewable by a select number of users. Unfortunately, I was at a loss as to how to accomplish this. I searched and found a lot of information about the subject but with limited skills I couldn't understand most of what I read. To further confuse me I was constantly reminded that most security measures were feeble when faced with a true assault on my valuable information.

While no method is 100% guaranteed to keep the bad guys out, there are some things that you can do to protect a page or a portion of your site from most prying eyes. This FAQ examines two steps to provide simple protection of a simple Web page.

Essentially I was wanting to create a page that only could be viewed by a few specific people. Hence, the first thing I needed to do was to create some means for a user to identify who they were. This step is called authentication, and I created a "login Web page" to accomplish this. This login Web page need be nothing more than a simple form with text boxes for username and password with a submit button. Sample code can be seen below - all that you'll need to change to get it working is to replace the form's action attribute with the appropriate ASP page that you wish to protect.

<form method="POST" action="pagename_to_protect.asp">
  <p align="center">Username <input type="text" name="username" size="20"><br>
  Password <input type="password" name="password" size="20"></p>
  <p align="center"><input type="submit" value="Log in" name="log_in"></p>

Then on the page you want to protect you would need to add at the top (before any HTML output):

  'Replace single quotes in username/password with two single quotes
  'to protect from SQL Injection Attack
  If Replace(request.form("username"),"'","''") <> "validname" AND _
        Replace(request.form("password"),"'","''") <> "validpassword" THEN
    Response.Redirect "my_login.htm"
  End if

Of course you can pretty up the pages any way you like but those are the basics. Is it perfect? No, but it will stop most amateurs. It does have some biting usability flaws, however. Essentially all that the page checks the Response.Form collection to see if there is a Username and Password that is allowed. Note that the above only allows one person to view the page. What if you have a number of people who are authorized to view the page? Using the above method you would have to add additional clauses to the If statement.

Additionally, the page checks for submitted form variables, meaning if anyone tries to visit this page without visiting the login page first, they will be automatically redirected to the login page. While this is a Good Thing for someone who is not authorized to view the page, someone who is authorized may find this annoying. That is, if they user logins in from my_login.htm, visits the page, perhaps navigates to another page, and then revisits the "protected" page, they'll be redirected back to my_login.htm, required to enter their username/password again.

We can do better than this! First let's examine how we can improve the usability by allowing the page to dynamically determine who is authorized to view the page and who is not. Rather than using a big If statement that checks for valid username/passwords, we can use a database that stores the valid username/passwords.

First things first: create an Access database named users.mdb. Create a table named my_users with three fields: ID, an autonumber; username, a Text field; and password, a Text field. Of course you can include any fields you like and capture
all sorts of data like date of last login, time spent logged on, and so on but for now let's just get the basics down. Once created place the database in a folder called \db, just above the root on your server.

Once again you'll need a login page just like the one above but this time let's change the action to validate_this_user.asp. The task of validate_this_user.asp is to determine if the username and password supplied are in the database; the code for that page would look like:

  dim conn
  dim strconn

  strconn = "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & _
        Server.MapPath("/db/users.mdb") 'change the path as necessary

  set conn = server.createobject("adodb.connection")
  conn.open strconn

  'Replace single quotes in username/password with two single quotes
  'to protect from SQL Injection Attack
  Username = Replace(Request("Username"), "'", "''")
  Password = Replace(Request("Password"), "'", "''")

  SQL = "SELECT * FROM my_users WHERE username = '" & username & "'" & _
        "AND password ='" & password & "'"
  set oRs = conn.Execute(SQL)

  If oRs.EOF then
    session("ID") = "my_session" 'any word you'd like
  End If

  Set conn = Nothing
  Set oRs = Nothing

Note here that we set a Session variable, ID, equal to some string (in the above code we chose the string "my_session," but it might be more sensical to store the user's Username). Recall that in the first protected page example we looked at the Request.Form collection was checked on the protected page to see if the user was authorized to view it, requiring to user to re-login each time he visited the page. Now that we use Session variables, once the user logs in they will remain logged in until their session expires (typcially 20 minutes after the user's last activity on the site).

For each Web page you wish to protect you would add at the top of the page:

  If session("ID") <> "my_session" THEN
    Response.Redirect "login.htm"
  End if

There you have it. Simple inexpensive database and code to protect any number of pages.

While none of this is 100% secure it is probably good enough for most everyday security. If you need more protection then do some research. There are almost as many security methods out there as here are web sites and everyone has their own favorite. This will at least get you started.

For more information be sure to check out these resources:

Information on User Authentication
Information on Security
Simple Authentication

Happy Programming

By Doug Down (Doug D)

FAQ posted by Scott Mitchell at 6/2/2002 2:18:24 PM to the Security category. This FAQ has been viewed 83,896 times.

Do you have a FAQ you'd like to suggest? Suggestions? Comments? If so, send it in! Also, if you'd like to be a FAQ Admin (creating/editing FAQs), let me know! If you are looking for other FAQs, be sure to check out the 4Guys FAQ and Commonly Asked Messageboard Questions!

Most Viewed FAQs:

1.) How can I format numbers and date/times using ASP.NET? For example, I want to format a number as a currency. (761643 views)
2.) I am using Access and getting a 80004005 error (or a [Microsoft][ODBC Microsoft Access Driver] The Microsoft Jet database engine cannot open the file '(unknown)' error) when trying to open a connection! How can I fix this problem? (207777 views)
3.) How can I convert a Recordset into an array? Also, how can I convert an array into a Recordset? (202549 views)
4.) How can I quickly sort a VBScript array? (196039 views)
5.) How can I find out if a record already exists in a database? If it doesn't, I want to add it. (156019 views)
6.) How do I display data on a web page using arrays instead of Do...While...MoveNext...???... (152331 views)
7.) When I get a list of all files in a directory via the FileSystemObject, they aren't ordered in any reasonable way. How can I sort the files by name? Or by size? Or by date created? Or... (140381 views)
8.) For session variables to work, must the Web visitor have cookies enabled? (110162 views)
9.) Can I send emails without using CDONTS? (107083 views)
10.) How can I take the result of a SELECT...MULTIPLE or a group of same-named checkboxes and turn it into a query? That is, if the user selects 3 answers, how can I construct a query that looks for all 3? (106308 views)
Last computed at 9/17/2007 3:22:00 AM

ASP.NET [1.x] [2.0] | ASPFAQs.com | Advertise | Feedback | Author an Article