Resetting Password with ASP.NET 2.0 Membership and Multiple Providers

Posted by Peter Kellner on February 15, 2007 · 4 mins read

If you ever have wanted to be able to programmatically change (reset) a users  password while at the same time continuing to be able to use the question and answer feature, this post is for you.  The problem is that if you use code like this:

 string username = "user";
 string password = "pass@word";
 MembershipUser mu = Membership.GetUser(username);
 mu.ChangePassword(mu.ResetPassword(), password);

You will find that if you have in your web.config requiresQuestionAnswer="true", you will get an error when you try and reset the password.  The elegant solution to this is to create an additional membeship tag in your web.config and reference it when you change passwords.  That is, add another provider like this:

<membership defaultProvider="SqlMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
    <clear/>
    <add name="SqlMembershipProviderOther" type="SqlProviderOneShot.SqlMembershipProvider"
    requiresQuestionAndAnswer="false"
     connectionStringName="EmailEmailConnectionString" applicationName="EmailEmail"
    enablePasswordRetrieval="false" enablePasswordReset="true"
    requiresUniqueEmail="true" passwordFormat="Hashed"
    minRequiredNonalphanumericCharacters="0" writeExceptionsToEventLog="false"
    minRequiredPasswordLength="1" passwordStrengthRegularExpression=""
    passwordAttemptWindow="10" maxInvalidPasswordAttempts="8"/>
</providers>
</membership>

Then, when you change your password, reference it as follows:


string username = "user";
string password = "pass@word";
MembershipUser mu = Membership.Providers["SqlMembershipProviderOther"].GetUser(username);
mu.ChangePassword(mu.ResetPassword(), password);

Hope this helps! At some point, I will integrate this functionality into my ObjectDataSource article that lets you display your membership information with a gridview or detailsview.