• Subscribe  RSS
  • About

Tayyab Bin Tariq

I like sharing what i know

  • Computer Programming
    • C++
  • Digital Image Processing
    • Matlab
  • FAST NUCES
  • Microsoft Technologies
    • Visual Studion .NET
    • Windows Forms
    • Workflow Foundation
    • WPF
  • Misc
  • Technology
  • Uncategorized
  • Web Development
    • PHP & MySQL
    • Security
  • WILT

Form Based Authentication in ASP.NET

If you like this post, please visit our sponsors above. Thanks!

This article demonstrates how to implement forms-based authentication by using a database to store the users.


Create an ASP.NET Application Using C# .NET

  1. Open Visual Studio .NET.
  2. Create a new ASP.NET Web application, and specify the name and location.

Configure the Security Settings in the Web.config File

This section demonstrates how to add and modify the <authentication> and <authorization> configuration sections to configure the ASP.NET application to use forms-based authentication.

  1. In Solution Explorer, open the Web.config file.
  2. Change the authentication mode to Forms.
  3. Insert the <Forms> tag, and fill the appropriate attributes. Copy the following code, and then click Paste as HTML on the Edit menu to paste the code in the <authentication> section of the file:
  4.    1: <authentication mode="Forms">

       2:    <forms name=".ASPXFORMSDEMO" loginUrl="logon.aspx" 

       3:    protection="All" path="/" timeout="30" />

       4: </authentication> 

       5:     

  5. Deny access to the anonymous user in the <authorization> section as follows:
   1: <authorization>

   2:    <deny users ="?" />

   3:    <allow users = "*" />

   4: </authorization>

Create a Logon.aspx Page

  1. Add a new Web Form to the project named Logon.aspx.
  2. Open the Logon.aspx page in the editor, and switch to HTML view.
  3. Copy the following code, and use the Paste as HTML option on the Edit menu to insert the code between the <form> tags:
  4.    1: <h3>

       2:    <font face="Verdana">Logon Page</font>

       3: </h3>

       4: <table>

       5:    <tr>

       6:       <td>Email:</td>

       7:       <td><input id="txtUserName" type="text" runat="server"></td>

       8:       <td><ASP:RequiredFieldValidator ControlToValidate="txtUserName"

       9:            Display="Static" ErrorMessage="*" runat="server" 

      10:            ID="vUserName" /></td>

      11:    </tr>

      12:    <tr>

      13:       <td>Password:</td>

      14:       <td><input id="txtUserPass" type="password" runat="server"></td>

      15:       <td><ASP:RequiredFieldValidator ControlToValidate="txtUserPass"

      16:           Display="Static" ErrorMessage="*" runat="server" 

      17:           ID="vUserPass" />

      18:       </td>

      19:    </tr>

      20:    <tr>

      21:       <td>Persistent Cookie:</td>

      22:       <td><ASP:CheckBox id="chkPersistCookie" runat="server" autopostback="false" /></td>

      23:       <td></td>

      24:    </tr>

      25: </table>

      26: <input type="submit" Value="Logon" runat="server" ID="cmdLogin"><p></p>

      27: <asp:Label id="lblMsg" ForeColor="red" Font-Name="Verdana" Font-Size="10" runat="server" />

      28:                         

  5. This Web Form is used to present a logon form to users so that they can provide their user name and password to log on to the application.
  6. Switch to Design view, and save the page.

Code the Event Handler So That It Validates the User Credentials

This section presents the code that is placed in the code-behind page (Logon.aspx.cs).

  1. Double-click Logon to open the Logon.aspx.cs file.
  2. Import the required namespaces in the code-behind file:
  3.    1: using System.Data.SqlClient;

       2: using System.Web.Security;

  4. Create a ValidateUser function to validate the user credentials by looking in the database. (Make sure that you change the Connection string to point to your database).
  5.    1: private bool ValidateUser( string userName, string passWord )

       2: {

       3:     SqlConnection conn;

       4:     SqlCommand cmd;

       5:     string lookupPassword = null;

       6:  

       7:     // Check for invalid userName.

       8:     // userName must not be null and must be between 1 and 15 characters.

       9:     if ( (  null == userName ) || ( 0 == userName.Length ) || ( userName.Length > 15 ) )

      10:     {

      11:         System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of userName failed." );

      12:         return false;

      13:     }

      14:  

      15:     // Check for invalid passWord.

      16:     // passWord must not be null and must be between 1 and 25 characters.

      17:     if ( (  null == passWord ) || ( 0 == passWord.Length ) || ( passWord.Length > 25 ) )

      18:     {

      19:         System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of passWord failed." );

      20:         return false;

      21:     }

      22:  

      23:     try

      24:     {

      25:         // Consult with your SQL Server administrator for an appropriate connection

      26:         // string to use to connect to your local SQL Server.

      27:         conn = new SqlConnection( "server=localhost;Integrated Security=SSPI;database=pubs" );

      28:         conn.Open();

      29:  

      30:         // Create SqlCommand to select pwd field from users table given supplied userName.

      31:         cmd = new SqlCommand( "Select pwd from users where uname=@userName", conn );

      32:         cmd.Parameters.Add( "@userName", SqlDbType.VarChar, 25 );

      33:         cmd.Parameters["@userName"].Value = userName;

      34:  

      35:         // Execute command and fetch pwd field into lookupPassword string.

      36:         lookupPassword = (string) cmd.ExecuteScalar();

      37:  

      38:         // Cleanup command and connection objects.

      39:         cmd.Dispose();

      40:         conn.Dispose();

      41:     }

      42:     catch ( Exception ex )

      43:     {

      44:         // Add error handling here for debugging.

      45:         // This error message should not be sent back to the caller.

      46:         System.Diagnostics.Trace.WriteLine( "[ValidateUser] Exception " + ex.Message );

      47:     }

      48:  

      49:     // If no password found, return false.

      50:     if ( null == lookupPassword ) 

      51:     {

      52:         // You could write failed login attempts here to event log for additional security.

      53:         return false;

      54:     }

      55:  

      56:     // Compare lookupPassword and input passWord, using a case-sensitive comparison.

      57:     return ( 0 == string.Compare( lookupPassword, passWord, false ) );

      58:  

      59: }

  6. You can use one of two methods to generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event. Sample code is provided for both scenarios. Use either of them according to your requirement.
    • Call the RedirectFromLoginPage method to automatically generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event:
    •    1: private void cmdLogin_ServerClick(object sender, System.EventArgs e)

         2: {

         3: if (ValidateUser(txtUserName.Value,txtUserPass.Value) )

         4:     FormsAuthentication.RedirectFromLoginPage(txtUserName.Value,

         5:         chkPersistCookie.Checked);

         6:     else

         7:         Response.Redirect("logon.aspx", true);

         8: }

    • Generate the authentication ticket, encrypt it, create a cookie, add it to the response, and redirect the user. This gives you more control in how you create the cookie. You can also include custom data along with the FormsAuthenticationTicket in this case.
       1: private void cmdLogin_ServerClick(object sender, System.EventArgs e)

       2: {

       3:    if (ValidateUser(txtUserName.Value,txtUserPass.Value) )

       4:    {

       5:       FormsAuthenticationTicket tkt;

       6:       string cookiestr;

       7:       HttpCookie ck;

       8:       tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now, 

       9: DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");

      10:       cookiestr = FormsAuthentication.Encrypt(tkt);

      11:       ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);

      12:       if (chkPersistCookie.Checked)

      13:       ck.Expires=tkt.Expiration;    

      14:             ck.Path = FormsAuthentication.FormsCookiePath; 

      15:       Response.Cookies.Add(ck);

      16:  

      17:       string strRedirect;

      18:       strRedirect = Request["ReturnUrl"];

      19:       if (strRedirect==null)

      20:             strRedirect = "default.aspx";

      21:          Response.Redirect(strRedirect, true);

      22:    }

      23:    else

      24:       Response.Redirect("logon.aspx", true);

      25: }

  7. Make sure that the following code is added to the InitializeComponent method in the code that the Web Form Designer generates:
   1: this.cmdLogin.ServerClick += new System.EventHandler(this.cmdLogin_ServerClick);

Create a Default.aspx Page

This section creates a test page to which users are redirected after they authenticate. If users browse to this page without first logging on to the application, they are redirected to the logon page.

  1. Rename the existing WebForm1.aspx page as Default.aspx, and open it in the editor.
  2. Switch to HTML view, and copy the following code between the <form> tags:
  3.    1: <input type="submit" Value="SignOut" runat="server" id="cmdSignOut">

  4. This button is used to log off the forms authentication session.
  5. Switch to Design view, and save the page.
  6. Import the required namespaces in the code-behind file:
  7.    1: using System.Web.Security;

  8. Double-click SignOut to open the code-behind page (Default.aspx.cs), and copy the following code in the cmdSignOut_ServerClick event handler:
  9.    1: private void cmdSignOut_ServerClick(object sender, System.EventArgs e)

       2: {

       3:    FormsAuthentication.SignOut();

       4:    Response.Redirect("logon.aspx", true);

       5: }

  10. Make sure that the following code is added to the InitializeComponent method in the code that the Web Form Designer generates:
  11.    1: this.cmdSignOut.ServerClick += new System.EventHandler(this.cmdSignOut_ServerClick);

  12. Save and compile the project. You can now use the application.

Share on FacebookShare on Facebook

If you like this post, please visit our sponsors blow. Thanks!

Posted April 30, 2009 by tayyabtariq. Comments and trackbacks are open. Follow the comments feed.
Filed under:
  • Security
  • Web Development
Tagged with: ASP.NET, Form Based Authentication, login, login security, Security, Visual Studio.NET.

Leave a Reply

Click here to cancel reply.

CAPTCHA Image CAPTCHA Audio
Refresh Image

← Windows Forms: Getting Started II
Linked List: Tutorial I →

Tags

Array Arrays Arrays of Arrays ASP.NET C# C++ callback callback functions Cookie Login cookies Digital Image Processing EventHandling Facebook getuserdata Google GUI Image Processing imread imshow Jagged Arrays login login security Matlab Matlab GUI Matlab GUI: Handling User Data and Images Matlab Image Matlab User Data MessageBox Microsoft PHP Authentication PHP Login PHP Members Area PushButton Ribbon Ribbon control Security session session variable setuserdata TextBox User Input Visual Studio.NET What I Learnt Today? Windows Forms WPF

Recent Posts

  • Arabian Idol: Our Arabic Language Project :)
  • How to block specific ports in Windows 7
  • Using unmanaged code/types from managed code
  • Ten things you shouldn’t post to Facebook
  • Matlab GUI-Radio Buttons: What I learnt Today?

Recent Comments

  • Nethsu on Create A Simple WPF Ribbon Control: What I learnt Today?
  • Bruno Laurinec on Using Ribbon Control with Windows Forms: What I Learnt Today?
  • Alex on Using Ribbon Control with Windows Forms: What I Learnt Today?
  • Srinivas on Using Ribbon Control with Windows Forms: What I Learnt Today?
  • ji seung Hoon on Using Ribbon Control with Windows Forms: What I Learnt Today?
  • XenoGlaux-Solutions

    • Ahsun Taquveem Chohan’s Blog
    • War On Technology
    • XenoGlaux-Solutions.com
  • Meta

    • Log in
    • Valid XHTML
  • Home
  • About
  • RSS Feed


Powered by WordPress and the PressPlay Theme

Copyright © 2010 Tayyab Bin Tariq