Software consultant, Developer, Codder : SharePoint, Office 365, ASP.NET, MVC, SharePoint, Javascript, JQuery, Ember JS, Angular JS, Entity Framework, Linq, HTML5, DotnetNuke, codding philosophy, blogger 7+ experience in codding and developing web applications, Code 4 Help..
31 December 2012
Custom Membership provider MVC
public class UserInfo
{
public int Id { get; set; }
[Required(ErrorMessage = "Please enter username")]
[Remote("UserExists", "Register")]
public string UserName { get; set; }
[Required(ErrorMessage = "Please enter password")]
public string Password { get; set; }
}
public class CustomMemberShipProvider : MembershipProvider
{
#region Data Initialization
//
// Properties from web.config, default all to False
//
private string _ApplicationName;
private bool _EnablePasswordReset;
private bool _EnablePasswordRetrieval = false;
private bool _RequiresQuestionAndAnswer = false;
private bool _RequiresUniqueEmail = true;
private int _MaxInvalidPasswordAttempts;
private int _PasswordAttemptWindow;
private int _MinRequiredPasswordLength;
private int _MinRequiredNonalphanumericCharacters;
private string _PasswordStrengthRegularExpression;
private MembershipPasswordFormat
_PasswordFormat = MembershipPasswordFormat.Hashed;
public override void Initialize(string name, NameValueCollection config)
{
if (config == null)
throw new ArgumentNullException("config");
if (name == null || name.Length == 0)
name = "CustomMembershipProvider";
if (String.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "Custom Membership Provider");
}
base.Initialize(name, config);
_ApplicationName =
GetConfigValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
_MaxInvalidPasswordAttempts =
Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5"));
_PasswordAttemptWindow =
Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10"));
_MinRequiredNonalphanumericCharacters =
Convert.ToInt32(GetConfigValue(config["minRequiredNonalphanumericCharacters"], "1"));
_MinRequiredPasswordLength =
Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "6"));
_EnablePasswordReset =
Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true"));
_PasswordStrengthRegularExpression =
Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], ""));
}
private UserInfoEntities _user = new UserInfoEntities();
public override int MaxInvalidPasswordAttempts
{
get { return _MaxInvalidPasswordAttempts; }
}
public override int MinRequiredNonAlphanumericCharacters
{
get { return _MinRequiredNonalphanumericCharacters; }
}
public override int MinRequiredPasswordLength
{
get { return _MinRequiredPasswordLength; }
}
public override int PasswordAttemptWindow
{
get { return _PasswordAttemptWindow; }
}
public override MembershipPasswordFormat PasswordFormat
{
get { return _PasswordFormat; }
}
public override string PasswordStrengthRegularExpression
{
get { return _PasswordStrengthRegularExpression; }
}
public override bool RequiresQuestionAndAnswer
{
get { return _RequiresQuestionAndAnswer; }
}
public override bool RequiresUniqueEmail
{
get { return _RequiresUniqueEmail; }
}
//
// A helper function to retrieve config values from the configuration file.
//
private string GetConfigValue(string configValue, string defaultValue)
{
if (string.IsNullOrEmpty(configValue))
return defaultValue;
return configValue;
}
public override string ApplicationName
{
get { return "/"; }
set { _ApplicationName = value; }
}
#endregion
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
var objdbuser = _user.UserInfoes
.Where(x => x.UserName.Equals(username)&&
x.Password.Equals(oldPassword)).FirstOrDefault();
if (objdbuser == null)
return false;
objdbuser.Password = newPassword;
_user.SaveChanges();
return true;
}
public override bool ChangePasswordQuestionAndAnswer(string username,
string password, string newPasswordQuestion, string newPasswordAnswer)
{
throw new NotImplementedException();
}
public override MembershipUser CreateUser(string username,
string password, string email, string passwordQuestion, string passwordAnswer,
bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
try
{
_user.UserInfoes.AddObject(new App_Data.UserInfo { Password = password,
UserName = username });
_user.SaveChanges();
status = MembershipCreateStatus.Success;
return GetUser(username, false);
}
catch (Exception)
{
status = MembershipCreateStatus.ProviderError;
return null;
}
}
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
var objdbuser = _user.UserInfoes
.Where(x => x.UserName.Equals(username)).FirstOrDefault();
if (objdbuser == null)
return false;
//TODO: Delete User
return true;
}
public override bool EnablePasswordReset
{
get { throw new NotImplementedException(); }
}
public override bool EnablePasswordRetrieval
{
get { throw new NotImplementedException(); }
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex,
int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex,
int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override int GetNumberOfUsersOnline()
{
throw new NotImplementedException();
}
public override string GetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override MembershipUser GetUser(string username, bool userIsOnline)
{
var objdbuser = _user.UserInfoes.Where(x => x.UserName
.Equals(username)).FirstOrDefault();
var user = new MembershipUser("CustomeMProvider",
objdbuser.UserName,
null,
objdbuser.UserName,
null,
null,
true,
false,
DateTime.MinValue,
DateTime.MinValue,
DateTime.MinValue,
DateTime.MinValue,
DateTime.MinValue);
return user;
}
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
throw new NotImplementedException();
}
public override string GetUserNameByEmail(string email)
{
var objdbuser = _user.UserInfoes
.Where(x => x.UserName.Equals(email)).FirstOrDefault();
if (objdbuser == null)
return objdbuser.UserName;
else
return string.Empty;
}
public override string ResetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override bool UnlockUser(string userName)
{
throw new NotImplementedException();
}
public override void UpdateUser(MembershipUser user)
{
var objdbuser = _user.UserInfoes
.Where(x => x.UserName.Equals(user.UserName)).FirstOrDefault();
if (objdbuser == null)
return;
//TODO: Update User Information
}
public override bool ValidateUser(string username, string password)
{
var objdbuser = _user.UserInfoes.Where(x => x.UserName.Equals(username)
&& x.Password.Equals(password)).FirstOrDefault();
if (objdbuser == null)
return false;
return true;
}
}
And
public class RegisterController : Controller
{
App_Data.UserInfoEntities _db = new App_Data.UserInfoEntities();
public ActionResult Login()
{
return View(new UserInfo());
}
[HttpPost]
public ActionResult Login(UserInfo objuser,
string returnUrl, FormCollection fc)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(objuser.UserName, objuser.Password))
{
var chkrember = false;
if (!string.IsNullOrEmpty(Convert.ToString(fc["chkrmber"])))
chkrember = Convert.ToBoolean(fc["chkrmber"]);
FormsAuthentication.SetAuthCookie(objuser.UserName, chkrember);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or
password provided is incorrect.");
}
}
return View(objuser);
}
public ActionResult Register()
{
return View(new UserInfo());
}
[HttpPost]
public ActionResult Register(UserInfo objuser)
{
if (!ModelState.IsValid)
return View(objuser);
MembershipCreateStatus createStatus;
Membership.CreateUser(objuser.UserName, objuser.Password,
objuser.UserName, passwordQuestion: null, passwordAnswer: null,
isApproved: true, providerUserKey: null, status: out createStatus);
if (createStatus != MembershipCreateStatus.Success)
{
ModelState.AddModelError("", "Error occurs in create user");
return View(objuser);
}
return new EmptyResult();
}
public JsonResult UserExists(string username)
{
var objuser = _db.UserInfoes
.Where(x => x.UserName.Equals(username)).FirstOrDefault();
if (objuser == null)
return Json(true, JsonRequestBehavior.AllowGet);
else
return Json(string.Format("an account for address {0} already exists.",
username), JsonRequestBehavior.AllowGet);
}
}
Hi, Ranmal: Thanks for such great article. It does help to understand custom membership provider. However, I do not get where is about "UserInforEntities" and "UserInfoes". Please provide more detailed code about these.
Hi, Ranmal: Thanks for such great article. It does help to understand custom membership provider. However, I do not get where is about "UserInforEntities" and "UserInfoes".
ReplyDeletePlease provide more detailed code about these.
Hi,
ReplyDeleteAll above code will work with entity framework.
UserInforEntities is a entityContex class object
UserInfoes is a entity in entityContext
Please let me know if need any more details.