Create User Using SqlMembershipProvider And Customizing Login Control - Part II
Bookmark
 

Rating: 0/5

 
Posted On: Mar 07 2009
Views: 3380
BookMarked: 0
Downloads: 88
 
 

In the previous artice, we discussed about configuring SqlMembershipProvider.
Our next step is to create a user and configure web.config for the membership provider.

Please add the following to the web.config for database connection string.
Data Source holds the name of the Sql server and initial catalog holds name of the database. If you have the database installed on your local machine and then use follow settings.


<configuration>

   <connectionStrings>

<add name="AspNetUserConn"

connectionString="Data Source=(local);

Initial Catalog=membership;Integrated Security=True" providerName="System.Data.SqlClient"/>

   </connectionStrings>

</configuration>

To add SqlMembershipProvider setting, use the following

<configuration>  

   <system.web>

      <membership defaultProvider="SqlMembershipProvider">

         <providers>

<add name="SqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="AspNetUserConn" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" applicationName="MembershipTestWebsite" requiresUniqueEmail="false" passwordFormat="Clear" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="1" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>

               

          </providers>

      </membership>

  </system.web>

</configuration>

We are referring connection string name in the membership provider. All values provided in the membership are loaded at the run time. You can have any number of providers with different settings. But you can have only one default provider. The default provider will be loaded at the runtime.

Using Asp.Net Website Administration Tool

Now, we create our first user using Built in Visual Studio Asp.Net Configuration Website.

In the Visual Studio, Select Asp.Net Configuration under Website menu.

 

It will open up a local website in your default browser. Now hit security tab.
User Create User Wizard to create a user for the website.


 Creating Login Page

Now drag and drop a Login control on a .aspx page. Use the setting as in figure.
This control takes user name and password, verifies against the database then redirects the user to the specified page if the login was successful.


 

Customizing Login Control

You can also customize Login control by adding your own controls to the LayoutTemplate. Login control will look for the controls named UserName,Password,FailureText etc. We may end in runtime error if we have different names.

    <asp:Login ID="Login1" runat="server" BackColor="#F7F7DE" BorderColor="#CCCC99"

        BorderStyle="Solid" BorderWidth="1px" CreateUserText="New user?" CreateUserUrl="~/CreateUser.aspx"

        DestinationPageUrl="~/Welcome.aspx" Font-Names="Verdana" Font-Size="10pt">

        <TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />

    </asp:Login>

    <br />

    <br />

    <h1>Customized Login Control</h1>

    <asp:Login ID="Login2" runat="server" Font-Names="Verdana" Font-Size="10pt" Width="440px" OnAuthenticate="Login2_Authenticate" OnLoggedIn="Login2_LoggedIn">

    <TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />

    <LayoutTemplate>

    <asp:Panel runat="server" ID="server" DefaultButton="btnLogin" BackColor="#6b9492" Width="440px">

        <table border="0" cellpadding="1" cellspacing="0" align="center" style="border-collapse: collapse;width:420px;">

           <tr>

               <td colspan="5" align="center" style="padding:10px">

                  <asp:Label ID="Label1" runat="server" Font-Size="Larger" ForeColor="whitesmoke" Text="Sign in to Code High Street" Font-Bold="true"></asp:Label>

               </td>                           

           </tr>

        </table>

        <table border="0" cellpadding="1" cellspacing="0" align="center" style="border-collapse: collapse;background-color:#F7F7DE;width:420px;">

           <tr>

            <td colspan="4" height="20px"></td>                                      

           </tr>

           <tr>

            <td width="10px"></td>

            <td colspan="4">

                <asp:Label ID="FailureText" runat="server" ForeColor="red" Font-Bold="true"></asp:Label>

            </td>                                                                               

           </tr>

           <tr>

            <td width="10px"></td>

            <td align="left">

                <asp:Label ID="lbUserName" runat="server" AssociatedControlID="UserName">Sign in Name:</asp:Label></td>

            <td colspan="2">

                <asp:TextBox ID="UserName" runat="server" TabIndex="1" Width="229px"></asp:TextBox>&nbsp;

            </td>

            <td>

                <asp:RequiredFieldValidator ID="rfvUserName" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="Login2">*</asp:RequiredFieldValidator></td>

           </tr>

           <tr>

           <td width="10px"></td>

           <td align="left">

           <asp:Label ID="lbPassword" runat="server" AssociatedControlID="Password">Password:</asp:Label></td>

           <td colspan="2">

           <asp:TextBox ID="Password" runat="server" TabIndex="2" TextMode="Password"></asp:TextBox>

           </td>                                      

           <td>

           <asp:RequiredFieldValidator ID="rfvPassword" runat="server" ControlToValidate="Password" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="Login2">*</asp:RequiredFieldValidator></td>

           </tr>

           <tr>

                <td width="10px"></td>

                <td align="right">

                </td>

                <td colspan="2">

                  <asp:CheckBox ID="cbRememberMe" runat="server" Text="Remember me next time." TabIndex="4" />

                </td>

                <td>

                </td>

           </tr>                                   

           <tr>

                <td width="10px"></td>

                <td align="right" style="height: 26px">

                </td>

                <td colspan="2" style="height: 26px">

                    <asp:Button ID="btnLogin" runat="server" CommandName="Login"

                        TabIndex="3" Text="Sign In" ValidationGroup="Login2"/></td>

                <td style="height: 26px">

                </td>

           </tr>

           <tr>

             <td colspan="2"></td>

             <td colspan="3" >

              <asp:HyperLink ID="hlForgotPassword" runat="server" NavigateUrl="~ForgottenPassword.aspx" Text="I cannot access my account" />                                     

             </td>                                      

           </tr>

           <tr>

                <td colspan="4" height="20px"></td>                                      

           </tr>

      </table>

      <br />

      <table border="0" cellpadding="1" cellspacing="0" align="center" style="border-collapse: collapse;background-color:#F7F7DE;width:420px;">

        <tr>

            <td align="center" style="padding-top:10px">

               <strong>Not a memeber yet? </strong>

            </td>               

        </tr>

        <tr>

            <td align="center" style="padding-bottom:10px">

                 <asp:HyperLink ID="hlNewUser" runat="server" NavigateUrl="~/CreateUser.aspx" Text="Join Now" />

            </td>               

        </tr>

                   

      </table>

      <br />

      </asp:Panel>

    </LayoutTemplate>

    </asp:Login>

 

The user credentials from the Cutomized Login Control can be validated using Membership.ValidateUser method.

protected void Login2_Authenticate(object sender, AuthenticateEventArgs e)

{

bool IsValidate = Membership.ValidateUser(Login2.UserName, Login2.Password);

      if (!IsValidate)

      {

            e.Authenticated = false;

            Login2.FailureText = "The username and/or password cannot be validated or has not been approved yet.";            

      }

      else

      {

            e.Authenticated = true;                     

      }

 }

In order to redirect to another page after a succesful login, use IsLogged event of the Login Control.

protected void Login2_LoggedIn(object sender, EventArgs e)

{

if (Request.QueryString["Url"] != null)

      {

       Response.Redirect("~/" + Request.QueryString["Url"].ToString());

      }

      else

      {

       Response.Redirect("~/Welcome.aspx");

      }

}

Now on your welcome page i.e., page which is displayed after successful login, add a LoginName control which displays the current logged username and add a LoginStatus control which diaplys Logout and LogIn Text based on their status. These controls are found under the Login tab of the Visual Studio toolbox.

<table>

<tr>

    <td>

Welcome,  <asp:LoginName ID="LoginName1" runat="server" />

    </td>

    <td>

[<asp:LoginStatus ID="LoginStatus1" runat="server"/>]

    </td>

</tr>

</table>

In order to deny the anonymous users, add the following to web.config file.

<configuration>

  <system.web>

    <authorization>

       <deny users="?"/>

    </authorization>

  </system.web>

</configuration>

 

You can also redirect user to set a particular page if his login expired or redirect a user if he is not authorized to view a page.

<configuration>

  <system.web>

     <authentication mode="Forms">

  <!--If access is denied then redirect to another page-->

  <forms loginUrl="default.aspx"/>

     </authentication>

  </system.web>

</configuration>

When you access CreateUser.aspx page, access will be denied. Since our web.config setting will redirect anonymous user. To give anonymous access to the CreateUser.aspx page, use the location tag to give access to a partcular page.

<configuration>

  <location path="CreateUser.aspx">

    <system.web>

      <authorization>

        <allow users="*"/>

      </authorization>

    </system.web>

  </location>

</configuration>


Membership class is implemented based on the Microsoft Provider Model. So it is easy to plug in without rebuilding entire website. It also comes with hands full of easy to customize settings. We will examine Sql Server Membership, Roles, Profiles in the later series.



Rate This Article

Please Sign In In to post messages.