Unit Testing Sqlite Membership Provider in MVC app - asp.net-mvc

I've created an MVC application and I've set up Roger Martin's sqlite Providers in place of the default Providers. I'm curious about how I would go about unit testing these.
Below is a stripped down method that has many validations, only one of which is still present. Among other things, I want to write tests that ensures one can't register if the username has been taken, and can register if the username is free (and other validations pass), etc.
I can see how unit tests could determine success or failure, but not failure for a specific reason, unless I check the output MembershipCreateStatus parameter but I'm not sure if there is a better way. Further, what I need to give for object providerUserKey? Any insight would be very helpful.
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
//some validations, and then:
MembershipUser u = GetUser(username, false);
if (u == null)
{
///register user
status = MembershipCreateStatus.Success;
return GetUser(username, false);
}
else
{
status = MembershipCreateStatus.DuplicateUserName;
}
return null;
}

Use the out MembershipCreateStatus status output variable to determine the reason of failure (duplicte username, invalid password, duplicate email, etc).
The value will be one of the following:
MembershipCreateStatus.Success
MembershipCreateStatus.DuplicateUserName
MembershipCreateStatus.DuplicateEmail
MembershipCreateStatus.InvalidPassword
MembershipCreateStatus.InvalidEmail
MembershipCreateStatus.InvalidAnswer
MembershipCreateStatus.InvalidQuestion
MembershipCreateStatus.InvalidUserName
MembershipCreateStatus.ProviderError
MembershipCreateStatus.UserRejected

Related

Change e-mail or password in AspNetUsers tables in ASP.NET Identity 2.0

I have implemented the ForgotPassword (with token reset) into my MVC 5 application. We are in production. Although this works in majority of the cases, many of our end-users are of older age and get confused when they cannot login and need a reset. So in those situations, I am considering giving one of our admin staff the ability to reset a user's password and giving them the new password on the phone. The data is not that sensitive.
I tried this:
public ActionResult ResetPassword()
{ UserManager<IdentityUser> userManager =
new UserManager<IdentityUser>(new UserStore<IdentityUser>());
var user = userManager.FindByEmail("useremail.samplecom");
userManager.RemovePassword(user.Id);
userManager.AddPassword(user.Id, "newpassword");
}
I get a cryptic error stating Invalid Column EMail, Invalid Column Email Confirmed ......
I also tried the userManager.ResetPassword(), but abandoned that idea because it needs a token reset. I want to bypass it.
What am I not seeing?
Thanks in advance.
I also tried the userManager.ResetPassword(), but abandoned that idea because it needs a token reset. I want to bypass it.
How about you just generate the token and pass it to the Reset routine ?
var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
var code = await userManager.GeneratePasswordResetTokenAsync("username");
var result = await userManager.ResetPasswordAsync("username", code, "your new password");
if (!result.Succeeded)
{
//password does not meet standards
}
The idea here is you are just emulating/bypassing the usual routine of sending the token to the client (via email) and having the link that they click on call ResetPasswordAsync
I'm not completely sure if this will work in your implementation but I use the following code with success in a use case which has basically the same requirements as yours. The difference is that I'm not letting any user reset it's own password. This is always the task of an admin.
I'm bypassing the ApplicationUserManager and edit the information directly in the table, using just Entity Framework.
// I created an extension method to load the user from the context
// you will load it differently, but just for completeness
var user = db.LoadUser(id);
// some implementation of random password generator
var password = General.Hashing.GenerateRandomPassword();
var passwordHasher = new Microsoft.AspNet.Identity.PasswordHasher();
user.PasswordHash = passwordHasher.HashPassword(password);
db.SaveChanges();
You have to get the user from the database and generate the code not by username :
public async Task<Unit> ResetPassword(string userName, string password)
{
if (!string.IsNullOrWhiteSpace(userName))
{
var returnUser = await _userManager.Users.Where(x => x.UserName == userName).FirstOrDefaultAsync();
var code = await _userManager.GeneratePasswordResetTokenAsync(returnUser);
if (returnUser != null)
await _userManager.ResetPasswordAsync(returnUser, code, password);
}
return Unit.Value;
}

Manually validating a password reset token in ASP.NET Identity

I would like to manually validate a password reset token in ASP.NET Identity 2.0. I'm trying to create my own version of UserManager.ResetPasswordAsync(string userId, string token, string newPassword) that takes and IdentityUser instead of userId like this:
UserManager.ResetPasswordAsync(IdentityUser user, string token, string newPassword)
Not sure if I am doing this right, but here I am attempting to validate the code that was emailed to the user in an earlier step. I have not modified the code/token that sends the email to the user and generates the code. I am assuming this is the correct method to call, but the purpose argument is incorrect. (I tried passing "ASP.NET Identity" but no dice.)
if (await userManager.UserTokenProvider.ValidateAsync(purpose: "?", token: code, manager: userManager, user: user))
{
return IdentityResult.Success;
}
else
{
return new IdentityResult("Invalid code.");
}
If someone could fill me in on the details of how it works out of the box, or point me at Microsoft's source code for UserManager.ResetPasswordAsync(IdentityUser user, string token, string newPassword) that would be most appreciated!
I overcame my problem by setting the purpose to "ResetPassword".
Below is a snippet of the final result in case someone wants to do something similar. It is a method in my ApplicationUserManager class. Realize, though, that some of the exception handling that Microsoft implements is missing or not localized because certain private variables, methods, and resources used in their code are inaccessible. It's unfortunate they did not make that stuff protected so that I could have gotten at it. The missing ThrowIfDisposed method call in particular is interesting (and bazaar) to me. Apparently they are anticipating method calls after an instance has been disposed in order to provide a friendlier error message and avoid the unexpected.
public async Task<IdentityResult> ResetPasswordAsync(IdentityUser user,
string token, string newPassword)
{
if (user == null)
{
throw new ArgumentNullException("user");
}
// Make sure the token is valid and the stamp matches.
if (!await UserTokenProvider.ValidateAsync("ResetPassword", token,
this, user))
{
return IdentityResult.Failed("Invalid token.");
}
// Make sure the new password is valid.
var result = await PasswordValidator.ValidateAsync(newPassword)
.ConfigureAwait(false);
if (!result.Succeeded)
{
return result;
}
// Update the password hash and invalidate the current security stamp.
user.PasswordHash = PasswordHasher.HashPassword(newPassword);
user.SecurityStamp = Guid.NewGuid().ToString();
// Save the user and return the outcome.
return await UpdateAsync(user).ConfigureAwait(false);
}
It appears that the code for Microsoft.AspNet.Identity has not been Open Sourced according to the Codeplex repository located at:
https://aspnetidentity.codeplex.com/SourceControl/latest#Readme.markdown
At present, the ASP.NET Identity framework code is not public and
therefore will not be published on this site. However, we are planning
to change that, and as soon as we are able, the code will be published
in this repository.
However I did find this which might be the source for the UserManager based on the debug symbols:
UserManager Source Code
I also found these posts which might help:
Implementing custom password policy using ASP.NET Identity
UserManager Class Documentation
IUserTokenProvider Interface Documentation

change password in MVC 4

I am building ASP.NET MVC 4 application. I use Simple Membership provider to manage authentication and authorization within the system. What are the ways of changing the password in this approach. I found a ChangePassword method which takes three parameters, including original password, to operate.
Is there any other way to override/change the password for the user without actually knowing original password?
ChangePassword is used when a user wants to change their password - and the current password is their evidence to allow this to happen (think Change Password Screen).
I think the most direct way to do this is to call WebSecurity.GeneratePasswordResetToken() and pass the result into WebSecurity.ResetPassword, along with the new password.
var token = WebSecurity.GeneratePasswordResetToken("UserName");
var result = WebSecurity.ResetPassword(token, "NewPassword");
There is a detailed article on how to implement password reset/change with SimpleMembership in MVC 4 here. It also includes source code you can download.
This examples uses email to send a URL to the user to click on for password reset. This is more secure than just having the user enter the old password and new password directly on the website because it is another verification of the user. This alleviates the scenario where someone gets a hold of the user password and locks them out by changing the password. This also allows the user to reset the password in the case where they have forgotten the password.
The code to send the email with the link would look something like this.
[AllowAnonymous]
[HttpPost]
public ActionResult ResetPassword(ResetPasswordModel model)
{
string emailAddress = WebSecurity.GetEmail(model.UserName);
if (!string.IsNullOrEmpty(emailAddress))
{
string confirmationToken =
WebSecurity.GeneratePasswordResetToken(model.UserName);
dynamic email = new Email("ChngPasswordEmail");
email.To = emailAddress;
email.UserName = model.UserName;
email.ConfirmationToken = confirmationToken;
email.Send();
return RedirectToAction("ResetPwStepTwo");
}
return RedirectToAction("InvalidUserName");
}
This creates an email that has a link to a Web API that accepts the token as the id that is passed in. When they click on the link it hits this method.
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation(string Id)
{
ResetPasswordConfirmModel model = new ResetPasswordConfirmModel() { Token = Id };
return View(model);
}
This action gets the token from the query string and puts it in the ResetPasswordConfirmationModel that is passed to the view which allows the user to enter the new password. The new password is entered twice to make sure they entered it correctly, which is validate on the page. When they submit this information they are taken to the POST version of this action which actually resets the password.
[AllowAnonymous]
[HttpPost]
public ActionResult ResetPasswordConfirmation(ResetPasswordConfirmModel model)
{
if (WebSecurity.ResetPassword(model.Token, model.NewPassword))
{
return RedirectToAction("PasswordResetSuccess");
}
return RedirectToAction("PasswordResetFailure");
}

.Net Membership Provider not catching email duplications

I am relatively new to .Net/MVC3, and am working on a C#, MVC3, EF4 application that makes use of the default membership provider. From my reading, it should automatically catch duplicate emails, but it does not seem to do so, and I'm not certain why. What I really need to figure out is where to look to see if the right pieces are in place, and for the reason(s) why it might not do that validation check (it seems to do most/all of the others, like duplicate user names, or invalid password formats, etc. with only duplicate email not getting caught.)
Customizations include adding new users to a specific role, and redirecting to a 'first time' welcome page.
Here is the code:
// POST: /Account/Register
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
Roles.AddUserToRole(model.UserName, "Registered");
//return RedirectToAction("Index", "Home");
return RedirectToAction("Acceptance", "Account");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Here are the (untouched) validation methods:
#region Status Codes
private static string ErrorCodeToString(MembershipCreateStatus createStatus)
{
// See http://go.microsoft.com/fwlink/?LinkID=177550 for
// a full list of status codes.
switch (createStatus)
{
case MembershipCreateStatus.DuplicateUserName:
return "User name already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A user name for that e-mail address already exists. Please enter a different e-mail address.";
etc.
By default, only usernames must be unique. If you want unique email addresses as well, then you must set that in the Web.config entry for the MembershipProvider.
something like
<membership>
<providers>
<add name="AspNetSqlMembershipProvider" [...] requiresUniqueEmail="true" [...] />
</providers>
</membership>
The only thing that comes to mind is making sure that model.Email has a value. Other thing you can check is look at the default membership provider tables in SQL server to check which values are being stored.

Where to store logged user information on ASP.NET MVC using Forms Authentication?

I'm using ASP.NET MVC and Forms Authentication on my application. Basically I use FormsAuthentication.SetAuthCookie to login and FormsAuthentication.SignOut to logout.
In the HttpContext.Current.User.Identity I have stored the user name but I need more info about the logged user. I don't want to store my entire User obj in the Session because it might be big and with much more infomation than I need.
Do you think it's a good idea to create like a class called LoggedUserInfo with only the attributes I need and then add it to the Session variable? Is this a good approach?
Or do you have better ideas?
I use this solution:
ASP.NET 2.0 Forms authentication - Keeping it customized yet simple
To summarize: I created my own IPrincipal implementation. It is stored in HttpContext.Current.Cache. If it is somehow lost, I have username from client side authorization cookie and can rebuild it. This solution doesn't rely on Session, which can be easily lost.
EDIT
If you want to use your principal in your controller and make it testable, you can do this:
private MyPrincipal _myPrincipal;
MyPrincipal MyPrincipal
{
get
{
if (_myPrincipal == null)
return (MyPrincipal)User;
return _myPrincipal;
}
set
{
_myPrincipal = value;
}
}
In your test, you will set object prepared for testing. Otherwise it will be taken from HttpContext. And now I started thinking, why do I use Ninject to do it?
Store it server side in the session.
Eg.
// Make this as light as possible and store only what you need
public class UserCedentials
{
public string Username { get; set; }
public string SomeOtherInfo { get; set; }
// etc...
}
Then when they sign in just do the following to save the users info:
// Should make typesafe accessors for your session objects but you will
// get the point from this example
Session["UserCredentials"] = new UserCredentials()
{ Username = "SomeUserName", SomeOtherInfo = "SomeMoreData" };
Then whenever you need it fetch it:
UserCredentials user = (UserCredentials)(Session["UserCredentials"]);
I have written a couple of question/answers regarding doing custom authorization in MVC:
How to implement authorization checks in ASP.NET MVC based on Session data?
How does the Authorize tag work? - Asp.net Mvc
I actually like to use a CustomPrincipal and CustomIdentity which I set in the logon action method like
if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password) && _authService.IsValidLogin(username, password))
{
User objUser = _userService.GetUserByName(username);
if (objUser != null)
{
//** Construct the userdata string
string userData = objUser.RoleName + "|" + objUser.DistrictID + "|" + objUser.DistrictName + "|" + objUser.ID + "|" + objUser.DisplayName;
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, rememberMe.GetValueOrDefault());
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Add(authCookie);
return RedirectToAction("Index", "Absence");
}
else
{
return RedirectToAction("LogOn", "Account");
}
}
else
{
return RedirectToAction("LogOn", "Account");
}
Then in the custom principal you can have methods that access specific information you passed in to the constructor like
((CustomIdentity)((CustomPrincipal)HttpContext.Current.User).Identity).DisplayName;
where the DisplayName property is declared in the CustomIdentity class.
Well you will have to store these somewhere. Two main possible places though:
The server
You can either put them into Session. I suggest you do create a separate class that will hold only data that you actually need to avoid of wasting too much memory. Or you can also store into Cache that can end up in having many DB calls when there are huge amounts of concurrent users.
The client
In this case if you can limit the amount of data with a separate class, to that and use whatever way to serialize it and send it to the client. Either in a cookie or in URI (if length permits and cookies are disabled)...
Outcome of these thoughts:
the main thing here would be to create a separate class if you gain much memory resources this way. So that's the first thing you should do.

Resources