How to allow e-mail and username authentication at the same time

   —   
This article shows you how to configure Kentico CMS to allow users to login using their e-mail address, or user name.
Article is based on this forum thread.

You need to override the default membership provider like this:
public class Class1 : CMS.MembershipProvider.CMSMembershipProvider { public override bool ValidateUser(string username, string password) { string siteName = CMSContext.CurrentSiteName; UserInfo result = AuthenticationHelper.AuthenticateUser(username, password, siteName); if (ValidationHelper.IsEmail(username)) { string name = GetUserNameByEmail(username); return (password == GetPassword(name, null)); } return base.ValidateUser(username, password); } }

Then in the web.config file, you need change the class reference to your custom class created above:
<membership defaultProvider="CMSProvider" userIsOnlineTimeWindow="30"> <providers> <clear/> <add name="CMSProvider" type="CustomMembership.Class1" connectionStringName="CMSConnectionString" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed"/> </providers> </membership>

The above code handles the authentication.  However, there is one more thing you need to override – the call of the default GetCurrentUser metod, because it is looking for the user name and not for the e-mail address:
public class CustomUserInfoProvider : UserInfoProvider { protected override UserInfo GetUserInfoInternal(string userName) { userName = SqlHelperClass.GetSafeQueryString(userName); InfoDataSet<UserInfo> dr = GetUsers("UserName = '"+ userName +"' OR Email ='"+ userName +"'", null); if (dr.Items.Count == 0) { return null; } return dr.Items[0]; } }

This code will return the user by e-mail.  The final step is to ensure the user info provider is used by handling it in the ApplicationStart event (in the CMSAppBase.cs file):
UserInfoProvider.ProviderObject = new CustomMembership.CustomUserInfoProvider();

-jo-


Applies to: Kentico CMS 7.x
Share this article on   LinkedIn