ASP.NET provides various ready-made controls for making our life easier. One of them is Login control. ASP.NET Login control can be used for displaying a standard UI for user login.. The control displays two textboxs for entering username/password and a checkbox for indicating whether to remember the user on this computer. The Login control does not by default allow to set whether to use username and password as the log in or email and password should be used. In this post I'll show how we can easily change this behavior and allow our members to use their email address while logging in.

 

Below is a sample markup of a Login control

<asp:Login ID="login" runat="server" 

UserNameLabelText="Email" OnAuthenticate="LogIn_OnAuthenticate">
   </asp:Login>
Here I haven't included any other irrelevant attributes in the markup. The two properties of interest are UserNameLabelText and OnAuthenticate event. The UserNameLabelText is the text displayed next to the field where the username is to be entered. This should be set to "email". The OnAuthenticate event fires when the user presses the log in button after providing the info. This is the place where we'll be doing our work. The handler for this event is given below.

Protected Sub LogIn_OnAuthenticate(ByVal o As Object, ByVal e As AuthenticateEventArgs)
Dim l As System.Web.UI.WebControls.Login
l = DirectCast(o, System.Web.UI.WebControls.Login)
Dim u As String = Membership.GetUserNameByEmail(l.UserName)
If String.IsNullOrEmpty(u) Then
e.Authenticated = False
Return
End If
If Membership.ValidateUser(u, l.Password) Then
e.Authenticated = True
l.UserName = u
Else
e.Authenticated = False
End If
End Sub
Here we are first casting the sender of the event to the proper type, Login control. Then we find the username with the given email by

Dim u As String = Membership.GetUserNameByEmail(l.UserName)
Then we return and set the Authenticated property to False if we do not find the user specified email

If String.IsNullOrEmpty(u) Then
e.Authenticated = False
Return
End If

Now we validate the username and password by calling the ValidateUser() method of Membership. If it validates, we set the Authenticated property of event parameter to true and set the Username property of Login control to the username

If Membership.ValidateUser(u, l.Password) Then
e.Authenticated = True
l.UserName = u
Else
e.Authenticated = False
End If

Note: it is very important to set Username property of the Login control to the username retrieved from the membership provider. Also, for this to work, email address should be unique and identify a unique user.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList