Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Forms authentication in asp.net and user registration - Part 91

Suggested Videos
Part 88 - Windows authentication and authorization
Part 89 - Windows authentication and folder level authorization
Part 90 - Forms authentication using user names list in web.config



In this code sample, we have used validation controls and ADO.NET. If you have not watched the videos on validation controls and ADO.NET, I would strongly encourage you to do so, before continuing with this session.

Please watch Part - 90, before proceeding. In Part - 90, we have discussed the basics of Forms authentication. One of the problems, with the example in Part 90, is that, we are not able to navigate to Registration/Register.aspx page if we are not logged in.

To solve this issue, add another web.config file to the "Registration" folder, and specify the authorization element to allow all users.
<authorization>
  <allow users="*"/>
</authorization>

At this point, without logging into the application, users should be able to navigate to Registration/Register.aspx page.



Copy and paste the following HTML in Register.aspx page.
<div style="font-family:Arial">
<table style="border: 1px solid black">
    <tr>
        <td colspan="2">
            <b>User Registration</b>
        </td>
    </tr>
    <tr>
        <td>
            User Name
        </td>    
        <td>
            :<asp:TextBox ID="txtUserName" runat="server">
            </asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorusername" 
            runat="server" ErrorMessage="User Name required" Text="*"
            ControlToValidate="txtUserName" ForeColor="Red">
            </asp:RequiredFieldValidator>
        </td>    
    </tr>
    <tr>
        <td>
            Password
        </td>    
        <td>
            :<asp:TextBox ID="txtPassword" TextMode="Password" runat="server">
            </asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorPassword" 
            runat="server" ErrorMessage="Password required" Text="*"
            ControlToValidate="txtPassword" ForeColor="Red">
            </asp:RequiredFieldValidator>
        </td>    
    </tr>
    <tr>
        <td>
            Confirm Password
        </td>    
        <td>
            :<asp:TextBox ID="txtConfirmPassword" TextMode="Password" runat="server">
            </asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorConfirmPassword" 
            runat="server" ErrorMessage="Confirm Password required" Text="*"
            ControlToValidate="txtConfirmPassword" ForeColor="Red" 
            Display="Dynamic"></asp:RequiredFieldValidator>
            <asp:CompareValidator ID="CompareValidatorPassword" runat="server" 
            ErrorMessage="Password and Confirm Password must match"
            ControlToValidate="txtConfirmPassword" ForeColor="Red" 
            ControlToCompare="txtPassword" Display="Dynamic"
            Type="String" Operator="Equal" Text="*">
            </asp:CompareValidator>
        </td>    
    </tr>
    <tr>
        <td>
            Email
        </td>    
        <td>
            :<asp:TextBox ID="txtEmail" runat="server">
            </asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail" 
            runat="server" ErrorMessage="Email required" Text="*"
            ControlToValidate="txtEmail" ForeColor="Red"
            Display="Dynamic"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail" 
            runat="server" ErrorMessage="Invalid Email" ControlToValidate="txtEmail"
            ForeColor="Red" Display="Dynamic" Text="*"
            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
            </asp:RegularExpressionValidator>
        </td>    
    </tr>
    <tr>
        <td>
                   
        </td>    
        <td>
            <asp:Button ID="btnRegister" runat="server" Text="Register" 
            onclick="btnRegister_Click"/>
        </td>    
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblMessage" runat="server" ForeColor="Red">
            </asp:Label>
        </td>    
    </tr>
    <tr>
        <td colspan="2">
            <asp:ValidationSummary ID="ValidationSummary1" ForeColor="Red" runat="server" />
        </td>    
    </tr>
</table>
</div>

Copy and Paste the following code in the "Register" button click event.
// If the Page has no validation errors
if (Page.IsValid)
{
    // Read the connection string from web.config.
    // ConfigurationManager class is in System.Configuration namespace
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    // SqlConnection is in System.Data.SqlClient namespace
    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand cmd = new SqlCommand("spRegisterUser", con);
        cmd.CommandType = CommandType.StoredProcedure;

        SqlParameter username = new SqlParameter("@UserName", txtUserName.Text);
        // FormsAuthentication calss is in System.Web.Security namespace
        string encryptedPassword = FormsAuthentication.
            HashPasswordForStoringInConfigFile(txtPassword.Text, "SHA1");
        SqlParameter password = new SqlParameter("@Password", encryptedPassword);
        SqlParameter email = new SqlParameter("@Email", txtEmail.Text);

        cmd.Parameters.Add(username);
        cmd.Parameters.Add(password);
        cmd.Parameters.Add(email);

        con.Open();
        int ReturnCode = (int)cmd.ExecuteScalar();
        if (ReturnCode == -1)
        {
            lblMessage.Text = "User Name already in use, please choose another user name";
        }
        else
        {
            Response.Redirect("~/Login.aspx");
        }
    }
}

Run the application. Fill in the required details, and click "Register" button. The user should be added to the database. In the next video session, we will discuss about, authenticating with the credentials we stored in the database.

9 comments:

  1. Where is the stored proc spRegisterUser

    ReplyDelete
    Replies
    1. CREATE PROC spRegisterUser @UserName NVARCHAR(100)
      ,@Password NVARCHAR(200)
      ,@Email NVARCHAR(200)
      AS
      BEGIN
      DECLARE @Count INT
      DECLARE @ReturnCode INT

      SELECT @Count = COUNT(UserName)
      FROM tblUsers
      WHERE UserName = @UserName

      IF @Count > 0
      BEGIN
      SET @ReturnCode = - 1
      END
      ELSE
      BEGIN
      SET @ReturnCode = 1

      INSERT INTO tblUsers
      VALUES (
      @UserName
      ,@Password
      ,@Email
      )
      END

      SELECT @ReturnCode AS ReturnValue
      END

      Delete
  2. Dear Sir,
    Can you show an example how to log into an intranet web application using domain user account and password? I am looking for an example where user needs to enter his or her active directory windows user id and password to log into an intranet web application. I believe it uses an LDAP.
    I am trying to create a login page under Visual Studio 2012.
    Thank you very much in advance for your help.

    ReplyDelete
    Replies
    1. set impersonate to true in web.config in it automatically uses built in user account and password and also set allow users="?" in authorization tag in web.config if u don't set impersonate to true it uses application pool identity

      Delete
  3. use impersonate to true it uses windows authentication

    ReplyDelete
  4. Don't use "SHA1" algorithm. It is already hacked. encripted password using "SHA1" paste to goodle then you can find the real password

    ReplyDelete
    Replies
    1. Severity Code Description Project File Line Suppression State
      Error CS0103 The name 'chkBoxRememberMe' does not exist in the current context HotVenusInternet C:\Users\HP\Documents\Visual Studio 2015\WebSites\HotVenusInternet\login.aspx.cs 28 Active

      Delete
  5. sir i want the code on the role of administrator in which he can do every thing and user has only limited access to his account or to some pages

    ReplyDelete
  6. please I need your help I do all the code here in right place but always I get this error when I try to connect to SQL server with windows authentication: "login failed for user ['Domain\user$']", I search for that problem in google but I Don't solve it until now any help please?!

    ReplyDelete

It would be great if you can help share these free resources