Search code examples
c#asp.netasp.net-membershipmembership-provider

asp.net get username of membership user when they are unauthenticated (reset password)


I am trying to implement a Reset Password function for an application in ASP.Net Membership.

In order to get the user in order to reset the password:

var user = Membership.GetUser(userNameFromSql, false);

However, this method only works when the user is authenticated. The point is moot if the reason the user wants to reset their password is if they can't log in? I'm therefore looking for an alternative to getting the Membership username when the user is not authenticated.

My reset password function is as follows. An SQL query is made to retrieve the username from the database, stored as userNameFromSql.

var user = Membership.GetUser(userNameFromSql, false);
string newPassword = txtNewPassword.Text;

if ((newPassword.Length >= Membership.MinRequiredPasswordLength) &&
    (newPassword.ToCharArray().Count(c => !Char.IsLetterOrDigit(c)) >=
            Membership.MinRequiredNonAlphanumericCharacters) &&
    ((Membership.PasswordStrengthRegularExpression.Length == 0) ||
            Regex.IsMatch(newPassword, Membership.PasswordStrengthRegularExpression)))
{
    user.ChangePassword(user.ResetPassword(), newPassword);
    lblMessage.Text = "Password Changed Successfully!";
    return true;
}

The page is accessed as a redirect from an email link containing a GUID for the password reset. The page is therefore verified, the userName from the database is also legal (i.e. there exists a valid user in the database who requested a password change), but I can't pass this user into the Membership.GetUser() method as it always returns NULL when the user is not authenticated.

How do I proceed? I hope this is sufficient information? Alternatively, could I manually reset the user's password by making an update query to the aspnetdb database (which holds the membership users), by hashing it using

crypto.hashPassword(string)

but the hashing method would have to be identical to Membership's own hashing method, otherwise it won't be able to retrieve the password again?

many thanks


Solution

  • Membership.GetUser(userNameFromSql, false) should work and actually Membership.GetUser(userNameFromSql) should be enough. If it returns null then your userNameFromSql is wrong.