Implementing Custom MembershipUser - asp.net

I am going round in circles and need some help in implementing a Custom MembershipUser so that I can add my own custom Properties to the MembershipUser.
I have been following the example on this site: How to: Implement a Custom Membership User
The problem I am having is in the constructor of CustomMembershipUser, I think.
My CustomMembershipUser has these three additional Properties: firstName, middleName, lastName.
public class CustomMembershipProvider : MembershipProvider
{
public override MembershipUser GetUser(string username, bool userIsOnline)
{
//.... Get data from database
MembershipUser baseUser = new MembershipUser(this.Name,
username,
userId,
email,
"",
comment,
isApproved,
isLockedOut,
dtCreate,
dtLastLogin,
dtLastActivity,
DateTime.Now,
dtLastLockoutDate);
return new CustomMembershipUser(baseUser, firstName, middleName, lastName)
}
}
public class CustomMembershipUser : MembershipUser
{
private string _firstName;
public string FirstName { get { return _firstName; } set { _firstName = value; } }
private string _middleName;
public string MiddleName { get { return _middleName; } set { _middleName = value; } }
private string _lastName;
public string LastName { get { return _lastName; } set { _lastName = value; } }
public CustomMembershipUser(MembershipUser baseuser, string firstname, string middlename, string lastname)
{
_firstName = firstname;
_middleName = middlename;
_lastName = lastname;
new CustomMembershipUser(baseuser); // DO I NEED THIS?? HOW TO IMPLEMENT??
}
}
I am calling it like so:
MembershipUser mu = Membership.GetUser(UserName);
CustomMembershipProvider p = (CustomMembershipProvider)Membership.Provider;
MembershipUser memUser = p.GetUser(UserName, true);
object userId = memUser.ProviderUserKey;
The ProviderUserKey is null and so are the other values.
How can I obtain the addition Properties I added?
Thanks

This is working for me:
public class CustomMembershipUser : MembershipUser
{
public CustomMembershipUser(
string providerName,
string name,
object providerUserKey,
string email,
string passwordQuestion,
string comment,
bool isApproved,
bool isLockedOut,
DateTime creationDate,
DateTime lastLoginDate,
DateTime lastActivityDate,
DateTime lastPasswordChangedDate,
DateTime lastLockoutDate
)
: base(providerName, name, providerUserKey, email, passwordQuestion,
comment, isApproved, isLockedOut, creationDate, lastLoginDate,
lastActivityDate, lastPasswordChangedDate, lastLockoutDate)
{
}
// Add additional properties
public string CustomerNumber { get; set; }
}
public class CustomMembershipProvider : MembershipProvider
{
public override MembershipUser GetUser(string username, bool userIsOnline)
{
if (string.IsNullOrEmpty(username))
{
// No user signed in
return null;
}
// ...get data from db
CustomMembershipUser user = new CustomMembershipUser(
"CustomMembershipProvider",
db.Username,
db.UserId,
db.Email,
"",
"",
true,
false,
db.CreatedAt,
DateTime.MinValue,
DateTime.MinValue,
DateTime.MinValue,
DateTime.MinValue);
// Fill additional properties
user.CustomerNumber = db.CustomerNumber;
return user;
}
}
// Get custom user (if allready logged in)
CustomMembershipUser user = Membership.GetUser(true) as CustomMembershipUser;
// Access custom property
user.CustomerNumber

Based on my own experience trying to do much of the same, trying to use the MembershipProvider to do this will be an ultimately frustrating and counterintuitive experience.
The idea of the membership provider model isn't to change or augment what the definition of a user is, as you're trying to do - it is to allow the Framework an alternate means of accessing the information that has already been defined as belonging to a "MembershipUser".
I think what you're really looking for is a user profile. Using ASP.NET profiles is boatloads easier than implementing your own provider. You can find the overview here.

Just so you know, I've tried to go down the MembershipProvider path before, and it's a long and windy one. You might see if just creating classes that implement IPrincipal and IIdentity will satisfy your needs, since they entail a lot less overhead.

Related

Disable User in ASPNET identity 2.0

I am looking for a way to disable the user instead of deleting them from the system, this is to keep the data integrity of the related data. But seems ASPNET identity only offers Delete Acccount.
There is a new Lockout feature, but it seems to lockout can be controlled to disable user, but only lock the user out after certain number of incorrect password tries.
Any other options?
When you create a site with the Identity bits installed, your site will have a file called "IdentityModels.cs". In this file is a class called ApplicationUser which inherits from IdentityUser.
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://devblogs.microsoft.com/aspnet/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates/ to learn more.
public class ApplicationUser : IdentityUser
There is a nice link in the comments there, for ease click here
This tutorial tells you exactly what you need to do to add custom properties for your user.
And actually, don't even bother looking at the tutorial.
add a property to the ApplicationUser class, eg:
public bool? IsEnabled { get; set; }
add a column with the same name on the AspNetUsers table in your DB.
boom, that's it!
Now in your AccountController, you have a Register action as follows:
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, IsEnabled = true };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
I've added the IsEnabled = true on the creation of the ApplicationUser object. The value will now be persisted in your new column in the AspNetUsers table.
You would then need to deal with checking for this value as part of the sign in process, by overriding PasswordSignInAsync in ApplicationSignInManager.
I did it as follows:
public override Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool rememberMe, bool shouldLockout)
{
var user = UserManager.FindByEmailAsync(userName).Result;
if ((user.IsEnabled.HasValue && !user.IsEnabled.Value) || !user.IsEnabled.HasValue)
{
return Task.FromResult<SignInStatus>(SignInStatus.LockedOut);
}
return base.PasswordSignInAsync(userName, password, rememberMe, shouldLockout);
}
Your mileage may vary, and you may not want to return that SignInStatus, but you get the idea.
The default LockoutEnabled property for a User is not the property indicating if a user is currently being locked out or not. It's a property indicating if the user should be subject to lockout or not once the AccessFailedCount reaches the MaxFailedAccessAttemptsBeforeLockout value. Even if the user is locked out, its only a temporary measure to bar the user for the duration of LockedoutEnddateUtc property. So, to permanently disable or suspend a user account, you might want to introduce your own flag property.
You don't need to create a custom property. The trick is to set the
LockoutEnabled property on the Identity user AND set the LockoutoutEndDateUtc to a future date from your code to lockout a user. Then, calling the UserManager.IsLockedOutAsync(user.Id) will return false.
Both the LockoutEnabled and LockoutoutEndDateUtc must meet the criteria of true and future date to lockout a user. If, for example, the LockoutoutEndDateUtc value is 2014-01-01 00:00:00.000 and LockoutEnabled is true, calling theUserManager.IsLockedOutAsync(user.Id) will still return true. I can see why Microsoft designed it this way so you can set a time span on how long a user is locked out.
However, I would argue that it should be if LockoutEnabled is true then user should be locked out if LockoutoutEndDateUtc is NULL OR a future date. That way you don't have to worry in your code about setting two properties (LockoutoutEndDateUtc is NULL by default). You could just set LockoutEnabled to true and if LockoutoutEndDateUtc is NULL the user is locked out indefinitely.
You would need to introduce your own flag into a custom IdentityUser-derived class and implement/enforce your own logic about enable/disable and preventing the user from logging in if disabled.
This all I did actually:
var lockoutEndDate = new DateTime(2999,01,01);
UserManager.SetLockoutEnabled(userId,true);
UserManager.SetLockoutEndDate(userId, lockoutEndDate);
Which is basically to enable lock out (if you don't do this by default already, and then set the Lockout End Date to some distant value.
Ozz is correct, however it may be adviseable to look at the base class and see if you can find a method that is checked for all signin angles - I think it might be CanSignIn?
Now that MS is open source you can see their implementation:
https://github.com/aspnet/AspNetCore/blob/master/src/Identity/src/Identity/SignInManager.cs
(Url has changed to:
https://github.com/aspnet/AspNetCore/blob/master/src/Identity/Core/src/SignInManager.cs)
public class CustomSignInManager : SignInManager<ApplicationUser>
{
public CustomSignInManager(UserManager<ApplicationUser> userManager,
IHttpContextAccessor contextAccessor,
IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory,
IOptions<IdentityOptions> optionsAccessor,
ILogger<SignInManager<ApplicationUser>> logger,
IAuthenticationSchemeProvider schemes) : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes)
{
}
public override async Task<bool> CanSignInAsync(ApplicationUser user)
{
if (Options.SignIn.RequireConfirmedEmail && !(await UserManager.IsEmailConfirmedAsync(user)))
{
Logger.LogWarning(0, "User {userId} cannot sign in without a confirmed email.", await UserManager.GetUserIdAsync(user));
return false;
}
if (Options.SignIn.RequireConfirmedPhoneNumber && !(await UserManager.IsPhoneNumberConfirmedAsync(user)))
{
Logger.LogWarning(1, "User {userId} cannot sign in without a confirmed phone number.", await UserManager.GetUserIdAsync(user));
return false;
}
if (UserManager.FindByIdAsync(user.Id).Result.IsEnabled == false)
{
Logger.LogWarning(1, "User {userId} cannot sign because it's currently disabled", await UserManager.GetUserIdAsync(user));
return false;
}
return true;
}
}
Also consider overriding PreSignInCheck, which also calls CanSignIn:
protected virtual async Task<SignInResult> PreSignInCheck(TUser user)
{
if (!await CanSignInAsync(user))
{
return SignInResult.NotAllowed;
}
if (await IsLockedOut(user))
{
return await LockedOut(user);
}
return null;
}
You can use these classes... A clean implemantation of ASP.NET Identity...
It's my own code. int is here for primary key if you want different type for primary key you can change it.
IdentityConfig.cs
public class ApplicationUserManager : UserManager<ApplicationUser, int>
{
public ApplicationUserManager(IUserStore<ApplicationUser, int> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<ApplicationContext>()));
manager.UserValidator = new UserValidator<ApplicationUser, int>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
manager.UserLockoutEnabledByDefault = false;
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser, int>(
dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
public class ApplicationSignInManager : SignInManager<ApplicationUser, int>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) :
base(userManager, authenticationManager) { }
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
public class ApplicationRoleManager : RoleManager<ApplicationRole, int>
{
public ApplicationRoleManager(IRoleStore<ApplicationRole, int> store)
: base(store)
{
}
}
public class ApplicationRoleStore : RoleStore<ApplicationRole, int, ApplicationUserRole>
{
public ApplicationRoleStore(ApplicationContext db)
: base(db)
{
}
}
public class ApplicationUserStore : UserStore<ApplicationUser, ApplicationRole, int,
ApplicationLogin, ApplicationUserRole, ApplicationClaim>
{
public ApplicationUserStore(ApplicationContext db)
: base(db)
{
}
}
IdentityModel.cs
public class ApplicationUser : IdentityUser<int, ApplicationLogin, ApplicationUserRole, ApplicationClaim>
{
//your property
//flag for users state (active, deactive or enabled, disabled)
//set it false to disable users
public bool IsActive { get; set; }
public ApplicationUser()
{
}
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
public class ApplicationUserRole : IdentityUserRole<int>
{
}
public class ApplicationLogin : IdentityUserLogin<int>
{
public virtual ApplicationUser User { get; set; }
}
public class ApplicationClaim : IdentityUserClaim<int>
{
public virtual ApplicationUser User { get; set; }
}
public class ApplicationRole : IdentityRole<int, ApplicationUserRole>
{
public ApplicationRole()
{
}
}
public class ApplicationContext : IdentityDbContext<ApplicationUser, ApplicationRole, int, ApplicationLogin, ApplicationUserRole, ApplicationClaim>
{
//web config connectionStringName DefaultConnection change it if required
public ApplicationContext()
: base("DefaultConnection")
{
Database.SetInitializer<ApplicationContext>(new CreateDatabaseIfNotExists<ApplicationContext>());
}
public static ApplicationContext Create()
{
return new ApplicationContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
I upvoted Watson, as there is another public method in SignInManager that accepts TUser user instead of string userName. The accepted answer only suggests overriding the method with the username signature. Both should really be overridden, otherwise there is a means of signing in a disabled user. Here are the two methods in the base implementation:
public virtual async Task<SignInResult> PasswordSignInAsync(string userName, string password, bool isPersistent, bool lockoutOnFailure)
{
var user = await UserManager.FindByNameAsync(userName);
if (user == null)
{
return SignInResult.Failed;
}
return await PasswordSignInAsync(user, password, isPersistent, lockoutOnFailure);
}
public virtual async Task<SignInResult> PasswordSignInAsync(User user, string password, bool isPersistent, bool lockoutOnFailure)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
var attempt = await CheckPasswordSignInAsync(user, password, lockoutOnFailure);
return attempt.Succeeded
? await SignInOrTwoFactorAsync(user, isPersistent)
: attempt;
}
Overriding CanSignIn seems like a better solution to me, as it gets called by PreSignInCheck, which is called in CheckPasswordSignInAsync. From what I can tell from the source, overriding CanSignIn should cover all scenarios. Here is a simple implementation that could be used:
public override async Task<bool> CanSignInAsync(User user)
{
var canSignIn = user.IsEnabled;
if (canSignIn) {
canSignIn = await base.CanSignInAsync(user);
}
return canSignIn;
}
In asp.net Core Identity v3, a new way of preventing a user from signing in has been added. Previously you could require that an account has a confirmed email address or phone number, now you can specify .RequireConfirmedAccount. The default implementation of the IUserConfirmation<> service will behave the same as requiring a confirmed email address, provide your own service to define what confirmation means.
public class User : IdentityUser<string>{
public bool IsEnabled { get; set; }
}
public class UserConfirmation : IUserConfirmation<User>
{
public Task<bool> IsConfirmedAsync(UserManager<User> manager, User user) =>
Task.FromResult(user.IsEnabled);
}
services.AddScoped<IUserConfirmation<User>, UserConfirmation>();
services.AddIdentity<User, IdentityRole>(options => {
options.SignIn.RequireConfirmedAccount = true;
} );
You need to implement your own UserStore to remove the identity.
Also this might help you.

How much of MembershipProvider do I *have* to override in MVC3

Until now I have done all authentication work in my MVC3 app, i.e. validate a member, and create a member, through my MemberRepository class. I would now like to go official, with a custom MembershipProvider. So far I have only gleaned that I really need to override this class's ValidateUser method, and since I am not using a Login control, I'm not even sure I absolutely have to do this.
Overriding methods like GetUser and CreateUser brings uninvited types to my party, like MembershipUser, where I have a finely crafted Member class. Please can someone clear up for me whether or not I really need a custom membership provider, if I'm not going to use any built-in controls or the admin tool, and if I do, should I confine my overrides to the absolutely necessary, which is what?
Here's one I wrote for unit testing. It's about as minimal as can be.
public class MockMembershipProvider : MembershipProvider
{
public IList<MembershipUser> Users { get; private set; }
private string _applicationName;
public override string ApplicationName
{
get
{
return _applicationName;
}
set
{
_applicationName = value;
}
}
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
throw new NotImplementedException();
}
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)
{
var user = new MembershipUser(ProviderName, username, username, email, passwordQuestion, null, isApproved, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);
Users.Add(user);
status = MembershipCreateStatus.Success;
return user;
}
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
var u = Users.Where(mu => mu.UserName.Equals(username, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (u == null) return false;
Users.Remove(u);
return true;
}
public override bool EnablePasswordReset
{
get { return false; }
}
public override bool EnablePasswordRetrieval
{
get { return false; }
}
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)
{
var users = (from u in Users
where u.UserName.Equals(usernameToMatch, StringComparison.OrdinalIgnoreCase)
select u).ToList();
totalRecords = users.Count;
return ToMembershipUserCollection(users);
}
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
var list = Users.Skip(pageIndex * pageSize).Take(pageSize);
totalRecords = list.Count();
var result = new MembershipUserCollection();
foreach (var u in list)
{
result.Add(u);
}
return result;
}
public override int GetNumberOfUsersOnline()
{
return Users.Count();
}
public override string GetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
return (from u in Users
where u.ProviderUserKey.ToString() == providerUserKey.ToString()
select u).FirstOrDefault();
}
public override MembershipUser GetUser(string username, bool userIsOnline)
{
return (from u in Users
where u.UserName.Equals(username, StringComparison.OrdinalIgnoreCase)
select u).FirstOrDefault();
}
public override string GetUserNameByEmail(string email)
{
return (from u in Users
where u.Email.Equals(email, StringComparison.OrdinalIgnoreCase)
select u.UserName).FirstOrDefault();
}
public override int MaxInvalidPasswordAttempts
{
get { return 3; }
}
public override int MinRequiredNonAlphanumericCharacters
{
get { return 1; }
}
public override int MinRequiredPasswordLength
{
get { return 6; }
}
public override int PasswordAttemptWindow
{
get { return 10; }
}
public override MembershipPasswordFormat PasswordFormat
{
get { throw new NotImplementedException(); }
}
public override string PasswordStrengthRegularExpression
{
get { return null; }
}
public override string Name
{
get
{
return ProviderName;
}
}
public string ProviderName { get; set; }
public override string ResetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override bool RequiresQuestionAndAnswer
{
get { return false; }
}
public override bool RequiresUniqueEmail
{
get { return true; }
}
private MembershipUserCollection ToMembershipUserCollection(IEnumerable<MembershipUser> users)
{
var result = new MembershipUserCollection();
foreach (var u in users)
{
result.Add(u);
}
return result;
}
public override bool UnlockUser(string userName)
{
return true;
}
public override void UpdateUser(MembershipUser user)
{
var oldUser = Users.Where(u => u.UserName.Equals(user.UserName, StringComparison.OrdinalIgnoreCase)).Single();
var index = Users.IndexOf(oldUser);
Users[index] = user;
}
public override bool ValidateUser(string username, string password)
{
throw new NotImplementedException();
}
public MockMembershipProvider()
{
this.ProviderName = "MockMembershipProvider";
Users = new List<MembershipUser>();
}
}
public class FakeMembershipProvider : MockMembershipProvider
{
public FakeMembershipProvider(string name)
{
this.ProviderName = name ?? "MockMembershipProvider";
}
public override MembershipUser CreateUser(
string username,
string password,
string email,
string passwordQuestion,
string passwordAnswer,
bool isApproved,
object providerUserKey,
out MembershipCreateStatus status)
{
status = MembershipCreateStatus.ProviderError;
var user = new MockMembershipUser();
user.Password = password;
user.User = username;
user.UserKey = providerUserKey;
Users.Add(user);
status = MembershipCreateStatus.Success;
return user;
}
}
public class MockMembershipUser : MembershipUser
{
public string Password { get; set; }
public string User { get; set; }
public object UserKey { get; set; }
public override string UserName { get { return User; } }
public override string Comment { get; set; }
public override object ProviderUserKey { get { return UserKey; } }
public override string GetPassword()
{
return Password ?? string.Empty;
}
Custom MembershipProvider
It is possible to get some nice security features "for free" if you're using a MembershipProvider: You can set up web.config to redirect every non-authenticated user to a login page, for instance. Or you can set up specific parts of the site to only be visible to users with specific roles. If these features don't make sense for your project, or if you're already implementing their equivalent in another way, there's not much point implementing a custom MembershipProvider.
SqlMembershipProvider
One other possibility you may want to consider is actually switching your own implementation to use the SqlMembershipProvider to handle membership functions.
The SqlMembershipProvider provides a robust, proven platform for the common tasks that are annoying to have to reinvent for every project: account creation, validation, deletion, locking, password resets, basic roles, etc. If you've already done all of this yourself without using the SqlMembershipProvider, there really isn't any point creating one just for the sake of having it. However, you should be careful, because there's a good chance that you've done something wrong in your own implementation. For example,
Are you storing passwords as plain text, or as hashes?
Are you open to Rainbow Table attacks, or are you salting your hashes?
Do you lock people's accounts after you've seen 50 or so invalid password attempts in a row, or do you let hackers just keep pounding away until they've brute-forced their way into someone's account?
The SqlMembershipProvider has already addressed all these issues in an easily configurable manner. You may want to have your own membership interfaces and DTOs simply wrap this default MembershipProvider just so you don't have to worry about these various concerns. That way, most of your code doesn't have to interact with these "uninvited types," but you still get the advantages of a widely-used and proven security framework on the back end.
Do you want to decouple your web application from MembershipRepository?
If so, implement all of the same functionality in a custom MembershipProvider so that your app will only depend on the .NET Membership classes (aside from your web.config).
If not, then don't bother.

Custom MembershipUser with only needed parameters

I am building a custom MembershipProvider more precisely the GetUser function.
Therefor i have a custom MembershipUser.
public class CustomMemberShipUser : MembershipUser
{
public CustomMemberShipUser (
string providerName,
string email,
object providerUserKey,
string name,
string passwordQuestion,
string comment,
bool isApproved,
bool isLockedOut,
DateTime creationDate,
DateTime lastLoginDate,
DateTime lastActivityDate,
DateTime lastPasswordChangedDate,
DateTime lastLockoutDate
): base(
providerName, email, providerUserKey, name, passwordQuestion,
comment, isApproved, isLockedOut, creationDate, lastLoginDate,
lastActivityDate, lastPasswordChangedDate, lastLockoutDate)
{
}
}
In the GetUser function of the MembershipProvider i get the user data and put them into the CustomMemberShipUser.
public override MembershipUser GetUser(string email, bool userIsOnline)
{
User u = _db.Users.Where(x => x.Email == email).First();
CustomMemberShipUser customUser = new CustomMemberShipUser (
"CustomMemberShipUser ",
u.Email,
u.id,
u.Email,
"",
"",
true,
false,
u.CreateDate,
DateTime.MinValue,
DateTime.MinValue,
DateTime.MinValue,
DateTime.MinValue);
return customUser ;
}
As you can see i use the email as name for the MemberShip and i don't need most of the other parameters.
Is there a way to make the call simpler? I don't want to initalize the MembershipUser with empty Strings and minimal Date values.
Thanks in advance
Could you adapt your CustomMembershipUser to do the 'padding' for you
public class CustomMemberShipUser : MembershipUser
{
public CustomMemberShipUser (
string email,
object providerUserKey,
): base(
"CustomMemberShipUser", email, providerUserKey, email, String.Empty,
String.Empty, true, false, DateTime.MinValue, DateTime.MinValue,
DateTime.MinValue, DateTime.MinValue, DateTime.MinValue)
{
}
}
It doesn't solve the problem but it will tidy up your provider which will become
public override MembershipUser GetUser(string email, bool userIsOnline)
{
User u = _db.Users.Where(x => x.Email == email).First();
CustomMemberShipUser customUser = new CustomMemberShipUser (u.Email, u.id);
return customUser ;
}
I presume your CustomMembershipUser is exposing some additional properties that you are not showing us. As it stands you could just return a MembershipUser. With the above the only benefit your CustomMembershipUser gives you is the cleaner construction in your CustomMembershipProvider

How do I wrap MembershipUser

How would i wrap MembershipUser so that the call below returns. Reason for wrapping is I would like the return result to be an interface to I can mock the user.
public IMembershipUser GetUser(string username, bool userIsOnline)
{
var user = Membership.GetUser(username, userIsOnline));
//Do something
return WrappedUser;
}
Thanks
I'm afraid you can't do this becuase..
System.Web.Security.MembershipUser type does not inherit from any special base-type and also it's not declared as partial, so there's no way you can do this.
But if you let us know what exactly you want to do, we can come up with alternate solutions.
You can achieve this by implementing your own SiteMembershipProvider. Here's an example snippet of an implementation I did a while back:
public class CustomMembershipUser : MembershipUser
{
public UserItem UserItem { get; private set; }
public CustomMembershipUser(string providerName, UserItem user)
: base(providerName, user.UserName, "user_" + user.UserID, user.Email,
null, null, true, !user.IsCurrent, DateTime.MinValue,
DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue)
{
this.UserItem = user;
}
}
public class SiteMembershipProvider : MembershipProvider
{
....
private static MembershipUser GetMembershipUser(UserItem user)
{
return new CustomMembershipUser(_membershipProviderName,user);
}
public override MembershipUser GetUser(string username, bool userIsOnline)
{
// Load user
return GetMembershipUser(foundUser);
}
....
}
In Web.Config:
<membership defaultProvider="SiteMembershipProvider">
<providers>
<clear/>
<add name="SiteMembershipProvider" type="SiteMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" connectionStringName="myConnectionString"/>
</providers>
</membership>
This should default your entire site to use the new MembershipProvider called SiteMembershipProvider.
Have a look here or here for an example to implement the entire class.
You could create a class which implements your IMemberShipUser interface and internally stores a reference to the "real" MembershipUser.
The properties and methods on your wrapped class could then simply delegate to the real reference.
Edit - A super simple example below:
using System.Web.Security;
namespace Example
{
public interface IMembershipUser
{
string UserName { get; }
string Email { get; }
}
public class WrappedMembershipUser: IMembershipUser
{
private readonly MembershipUser realUser;
public WrappedMembershipUser(MembershipUser realUser)
{
this.realUser = realUser;
}
public string UserName
{
get { return realUser.UserName; }
}
public string Email
{
get { return realUser.Email; }
}
}
}

How to change user password?

How to change user password for logged in user (and any field in user profile) if I use Silverlight Business Application?
There is no built in mechanism to change password in Silverlight.
You need to implement your own service for that.
For example:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class SecurityService : ISecurityService
{
public bool ChangePassword(string oldPassword, string newPassword)
{
if(!HttpContext.Current.User.Identity.IsAuthenticated)
return false;
return Membership.Provider.ChangePassword(HttpContext.Current.User.Identity.Name, oldPassword, newPassword);
}
...
}
If this answers your question, please "mark it as answer".
So, I created Domain Service with only one method:
[EnableClientAccess()]
public class DomainChangePassword : DomainService
{
[ServiceOperation]
public bool UserChangePassword(string userName, string oldPassword, string newPassword)
{
if (Membership.ValidateUser(userName, oldPassword))
{
MembershipUser memUser = Membership.GetUser(userName);
return memUser.ChangePassword(oldPassword, newPassword);
}
return false;
}
}
try:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class SecurityService : ISecurityService
{
public bool ChangePassword(string oldPassword, string newPassword)
{
if(!HttpContext.Current.User.Identity.IsAuthenticated)
return false;
return Membership.Provider.ChangePassword(HttpContext.Current.User.Identity.Name, oldPassword, newPassword);
}
...
}

Resources