Changing the PasswordFormat

I have been working with the Membership Provider most of the day.  Honestly I think that is way too long, so here is a quick summary of one item that too a little too long to troubleshoot.

OK, the default passwordformat is Hashed.  Great, encrypted passwords in the database, that sounds nice and secure.  Wait, if you use Hased PasswordFormat, you can not retrieve the password, which makes programtically changing a username sort of hard.  Basically what I have determined for now is that if you need to change a username you simply create a new user with the new username and delete the old one. 

There is a changepassword method on the MembershipUser class, but you can only use it if you have the old password.  So this gets me back to the GetPassword method, that only works for the passwordformat of Clear.

I tried to use Encrypted, but ran into a whole new set of errors.  You can use the reset password to get a randomly generated password, which I suppose would work, but I don't know.  That would probably be a better choice for this.

But the real problem I ran into was I changed the format to clear and I thought the Membership Provider would now use Clear password formats.  It does not, well it does, but not for existing members.  If you examine the Membership's tables, there is a PasswordFormat field, 0=Clear, 1=Hashed and 2=Encrypted.  When you go to retrieve the password, if it is Hashed for that user you will still throw a System.Configuration.Provider.ProviderException.  So I guess the wise thing to do is to catch that exception, reset the password when needed and reset the password like this:

'mu is the MembershipUser

'txtPwd is the textbox with out new password in it.

If mu.ChangePassword(mu.ResetPassword(), txtPwd.Text) = False Then

ltlMessage.Text = 'Your password could not be updated.'

Exit Sub

End If

The reason this should work it that you are resetting the the password anyway, so by calling resetpassword you are forcing the membership provider to create a random temporary password you can then use to actually set the password to what you want.  I honestly think this might be too much work for this.  What can I say, I tested and it works.

Now this is a little trick that I learned in this process.  If you change your web.config to use a different password format, say Hashed to Clear like I did.  I could not retrieve the password, which could be a problem if your users require this feature.  This was because the actual profile was stilled in hashed format.  If you actually go to the database and pull up the profile for the member you can see the passwordformat is still = 1.  If you change this to 0 it will now be considered in clear format and you can retreive the password, which is the Hashed string.  Not pretty, but it works.  The moral is know what format you plan on using.

Share This Article With Your Friends!