Saturday 4 August 2007

ASP.Net Membership: How To Log A User In By Email Address

Great as ASP.Net 2.0 Membership and Login Controls are sometimes they fall short in functionality. A common requirement is to allow users to log-in by email address. No problem with this snippet:
void LogUserIn (string email, string password)
{
   string username = Membership.GetUserNameByEmail(email);
   if (username != null
       && Membership.ValidateUser(username, password))
   {      
       // successfully authenticated
       FormsAuthentication.RedirectFromLoginPage(username, false);
   }
   else
   {
       // Display login error
   }
}
Remember - this only makes sense if you have set the MembershipProvider's RequiresUniqueEmail property to true. Otherwise Membership.GetUserNameByEmail will simply return the first username for the email address.

No comments :