Authenticating Users


The ASP.NET job site uses Forms authentication to authenticate users. Forms authentication is enabled for the site by including the Web.Config file in Listing 30.2 in the root directory of the site.

Listing 30.2 Web.Config
 <configuration>   <appSettings>     <add key="constring"       value="Server=localhost;UID=AspNETJobsUser;PWD=secret; Database=AspNetJobs" />   </appSettings>   <system.web>   <authentication mode="Forms" >   <forms name=".ASPNETJOBS"     loginUrl="/aspnetjobs/site/password/login.aspx" />   </authentication>   </system.web> </configuration> 

The C# version of this code can be found on the CD-ROM.

Forms authentication is configured in the authentication section in Listing 30.2. This authentication section sets the authentication mode to Forms . It also specifies the login page where unauthenticated users are automatically redirected when they request a password-protected page.

NOTE

To learn more about Forms authentication, see Chapter 19, "Using Forms-Based Authentication."


Notice that the Web.Config file in Listing 30.2 does not contain an authorization section. Anonymous users can access any page within the job site except those pages in a directory named password. The password directory contains a separate Web.Config file that contains an authorization section that prevents anonymous access to pages in that directory. The Web.Config file in the password subdirectory is included in Listing 30.3.

Listing 30.3 Password\Web.Config
 <configuration>   <system.web>   <authorization>     <deny users="?" />   </authorization>   </system.web> </configuration> 

The C# version of this code can be found on the CD-ROM.

The Web.Config file in Listing 30.3 contains an authorization section that denies access to all anonymous users (anonymous users are represented in the Web.Config file with the special symbol "?").

The password directory includes pages that require authentication, such as the ListResume.aspx and ListJob.aspx pages. If you try to request one of these pages, and you can't be identified by the Forms Authentication module, you are automatically redirected to the Login.aspx page (also included in the password directory).

The login.aspx page enables you to log in, if you are an existing user , or click a link to navigate to the register.aspx page, if you are a new user (see Figure 30.2). The login.aspx page is contained in Listing 30.4.

Listing 30.4 Site\Password\Login.aspx
 <!-- #INCLUDE Virtual="/aspnetjobs/site/includes/header.aspx" --> <Script runat="Server"> Sub Page_Load   Dim strReturnUrl As String   If Not IsPostBack Then     strReturnUrl = Request.QueryString( "ReturnUrl" )     lnkRegister.NavigateUrl = _       String.Format( _         "/aspnetjobs/site/register.aspx?ReturnUrl={0}", _         Server.URLEncode( strReturnUrl ) )   End If End Sub Sub Button_Click( s As Object, e As EventArgs )   If isValid Then   Select Case VerifyPassword( txtUsername.Text, txtPassword.Text )   Case 0     FormsAuthentication.RedirectFromLoginPage( txtUsername.Text, chkPersist.Checked )   Case 1     lblError.Text = "You did not enter a registered username"   Case 2     lblError.Text = "You did not enter a valid password"   End Select   End If End Sub Function VerifyPassword( strUsername, strPassword ) As Integer   Dim strConString As String   Dim conJobs As SqlConnection   Dim cmdVerify As SqlCommand   Dim parmReturn As SqlParameter   strConString = ConfigurationSettings.AppSettings( "constring" )   conJobs = New SqlConnection( strConString )   cmdVerify = New SqlCommand( "VerifyPassword", conJobs )   cmdVerify.CommandType = CommandType.StoredProcedure   parmReturn = cmdVerify.Parameters.Add( "@return", SqlDbType.Int )   parmReturn.Direction = ParameterDirection.ReturnValue   cmdVerify.Parameters.Add( "@username", strUsername )   cmdVerify.Parameters.Add( "@password", strPassword )   conJobs.Open()     cmdVerify.ExecuteNonQuery()   conJobs.Close()   Return cmdVerify.Parameters( "@return" ).Value End Function </Script> <myControls:Header   pageTitle="Please Login"   Runat="Server" /> <form runat="Server"> <table cellpadding="10" cellspacing="15"   border="0"> <tr><td> <h3>Login</h3> <asp:Label   ID="lblError"   EnableViewState="False"   forecolor="red"   font-bold="True"   runat="Server" /> <p> <b>Username:</b> <br> <asp:TextBox   ID="txtUsername"   CssClass="formfield"   runat="Server" /> <asp:RequiredFieldValidator   ControlToValidate="txtUsername"   Text="Required!"   runat="Server" /> <p> <b>Password:</b> <br> <asp:TextBox   ID="txtPassword"   TextMode="password"   CssClass="formfield"   runat="Server" /> <asp:RequiredFieldValidator   ControlToValidate="txtPassword"   Text="Required!"   runat="Server" /> <p> <asp:Button   Text="Login!"   OnClick="Button_Click"   runat="Server" /> <p> <asp:CheckBox   ID="chkPersist"   Checked="True"   runat="Server" /> Automatically remember me </td><td valign="top"> <h3>Register</h3> Are you a new user? <p> <asp:HyperLink   ID="lnkRegister"   Text="Click here to register!"   runat="Server" /> <p> It's free and it only takes a minute. </td></tr> </table> </form> <myControls:Footer   runat="Server"/> 

The C# version of this code can be found on the CD-ROM.

Figure 30.2. The Login page.

graphics/30fig02.jpg

If you enter a username and password in the login form contained in Listing 30.4, the Button_Click subroutine is executed. This subroutine passes the username and password entered into the form to a SQL stored procedure named VerifyPassword . The VerifyPassword stored procedure is included in Listing 30.5.

Listing 30.5 VerifyPassword
 CREATE PROCEDURE VerifyPassword (   @username Varchar( 20 ),   @password Varchar( 20 ) ) AS DECLARE @foundUser Varchar( 20 ) SELECT @foundUser = ul_username   FROM UserList   WHERE ul_username = @username   AND ul_password = @password IF @foundUser IS NOT NULL   Return 0 ELSE   IF Exists( SELECT ul_username     FROM UserList WHERE ul_username = @username )     Return 2   ELSE     RETURN 1 

The C# version of this code can be found on the CD-ROM.

The VerifyPassword stored procedure matches a username and password against a table named UserList . The stored procedure returns one of three possible values:

  • ” When the username and password combination is matched in the UserList table.

  • 2 ” When the username is found, but the password is invalid.

  • 1 ” When the username cannot be found in the UserList table.

The Login.aspx page displays different error messages depending on the value returned by the VerifyPassword stored procedure. When a person attempting to login cannot be authenticated against the database, the person is given an exact reason.

The Login.aspx page also enables new users to link to the Register.aspx page. The Register.aspx page contains a form for registering at the ASP.NET job site (see Figure 30.3). When a new user registers, the AddUser stored procedure is executed and the new user is added to the UserList database table. The AddUser stored procedure is contained in Listing 30.6.

Listing 30.6 AddUser
 CREATE procedure AddUser (   @username Varchar( 20 ),   @password varchar( 20 ),   @firstname varchar( 30 ),   @lastname varchar( 30 ),   @email varchar( 255 ),   @briefdesc varchar( 50 ),   @fulldesc Text,   @isresume Bit ) As If Exists( SELECT ul_username FROM UserList            WHERE ul_username = @username )   RETURN -1 ELSE   INSERT UserList (     ul_username,     ul_password,     ul_firstname,     ul_lastname,     ul_email,     ul_briefdesc,     ul_fulldesc,     ul_isresume   ) VALUES (     @username,     @password,     @firstname,     @lastname,     @email,     @briefdesc,     @fulldesc,     @isresume   ) 

The C# version of this code can be found on the CD-ROM.

Figure 30.3. The Register page.

graphics/30fig03.jpg

The AddUser stored procedure does one of two things. If the username passed to the stored procedure already exists in the UserList database table, the stored procedure returns the value -1 . You don't want two users to be assigned the same username. So, if someone attempts to register with a username that has already been taken, an error message is displayed on the Register.aspx page.

If the username does not already exist in the UserList table, the AddUser stored procedure adds the new user to the table. After the user is added, the user can log in by using the username and password combination at any point in the future.



ASP.NET Unleashed
ASP.NET 4 Unleashed
ISBN: 0672331128
EAN: 2147483647
Year: 2003
Pages: 263

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net