Beginners Guide to Forms Authentication in ASP.NET

There are four basic parts to simple forms authentication. Those parts are:

  1. The form (to gather user ID & pwd) itself
  2. The Web.Config File entry
  3. The Data Store (the place where you keep the usernames and passwords
  4. The Validation Process, triggered in the click event of the form.

Here is an example of the simplest of Forms (let’s call the page ‘Login.aspx’), designed to gather the user ID and password:

<table> <tr> <td align="Right" valign="Top"><b>User ID: </b></td> <td align="Left" valign="Top"> <asp:TextBox id="txtUID" Runat="server" /> </td> </tr> <tr> <td align="Right" valign="Top"><b>Password: </b></td> <td align="Left" valign="Top"> <asp:TextBox id="txtPWD" TextMode="Password" Runat="server" /> </td> </tr> <tr> <td align="Right" valign="Top" Colspan="2"> <asp:Button id="submitButton" Text="Login" onclick="doLogin" Runat="server" /> </td> </tr> </table>

In the Web.Config file, add this:

<authentication mode="Forms"> <forms name=".FormName" loginUrl="login.aspx" ' remember how we named the page for the form? protection="All" timeout="480" path="/" /> </authentication> <authorization> <deny users ="?" /> </authorization>

For the DataStore – you can use anything you’d like – however, I’m a bit partial to databases for quick interaction, so this example will be using a database. You’ll need to create a table in your database to store your names, User ID and Passwords. Here’s a list of the basic table fields you’ll need:

Field Name DataType Notes
id Integer (for Access, use AutoNumber; for SQL Server, create Identity)
Name MS Access: Text; SQL Server: VarChar use a length you feel is appropriate
- you can also make this two fields (First and Last names) to be able to more easily use their first name other places on the site, once they’re logged in
Login MS Access: Text; SQL Server: Varchar, unless you want an exact number of characters.
Password (same as above)

For the actual work to do this, create a click event for the button in the form. Let’s call it ‘doLogin’. Also, you’ll create a Function to do the validation – - let’s call it ‘ValidateUser’, with a couple of arguments, ‘uid‘ and ‘pwd‘. Also, create a label with an ID of ‘lblError’, just in case the login attempt fails.
Continues…

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>