ASP.NET Login by username or email

13. June 2011 19:21

Something that isn't support by default in asp.net is the ability to have end users login using either their username or their email address. Though it is somewhat easy to add this support using this little trick to override the normal login procedure on the login control.

 

To get started we will need our aspx page with a login control as follows.

 

<asp:Login runat="server" ID="Login2" DisplayRememberMe="false" 
    DestinationPageUrl="/Users/Default.aspx" onloggingin="Login2_LoggingIn" >
</asp:Login>

 

We can then override the default action in the event handler if we cannot find the current user trying to login and the username contains an '@' symbol.

 

 

public partial class Login : AppPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Login2_LoggingIn(object sender, LoginCancelEventArgs e)
    {
        if (Login2.UserName.Contains("@") && Membership.GetUser(Login2.UserName) == null)
        {
            string Username = Membership.GetUserNameByEmail(Login2.UserName);
            if (Username == null)
                return;

            if (Membership.ValidateUser(Username, Login2.Password) == true)
            {
                FormsAuthentication.SetAuthCookie(Username, false);
                FormsAuthentication.RedirectFromLoginPage(Username, false);
                e.Cancel = true;
            }
        }
    }
}

 

Note: if you are going to use the above you will need to make sure that your configured provider has a unique set of email addresses per user.

E-mail Kick it! DZone it! del.icio.us Permalink