ASP.NET Membership - Change password without asking the old

Recently I was in a situation where a user was required to change the password upon first login.

But MembershipUser’s ChangePassword requires 2 arguments. Old and new password. In my case the password was hashed and I couldn’t retrieve it unless the user enter it.

changepass

So I wanted to change the password without asking the old one. The solution was :

image

  1. Reset the password
  2. Keep the generated password in a variable
  3. Call MembershipUser.ChangePassword using the generated password as the old one!

It does an extra query to the database but does the job!

If the password was stored in Clear or Encrypted form it could be retrieved by calling user.GetPassword().

14 Comments

  • 



Anon

    Perfect!!

  • 



Anon

    //This is sufficent!

    MembershipUser user = Membership.GetUser();

    string genPasswrd = user.ResetPassword();

    sendEmail(genPasswrd);

  • 



djsolid

    @Anon No it's not if you want the user to specify the new password. It's OK in a "Forgot Password" scenario not in a "Change Password by Admin" scenario.

  • 



sushma

    i tried d same. but it is throwing "Object reference not set to an instance of an object." exception

  • 



djsolid

    Probably user is null because it's not authenticated. Try using the overload method which is Membership.GetUser(username)

  • 



joseduc

    I would just use "user.ChangePassword(user.GetPassword(), newPassword)"

  • 



cvantuss

    @joseduc that works fine if you have clear text passwords, which you never should.

    @djsolid thanks, this is exactly what I needed!

  • 



ugur

    i fixed my web.config.i got that error.
    what should i do ?
    Hashed passwords cannot be decoded.

  • Ashish Patel on said

    Reply
    



Ashish Patel

    MembershipUser user = Membership.GetUser();
    string genPasswrd = user.ResetPassword();

    in order to work this code,
    change web config file with following content

    requiresQuestionAndAnswer="false"

    then this code is going to be work.

  • 



<a href="http://ww.sledgedev.com" rel="nofollow">barrett breshears</a>

    God Bless you sir.

  • Bruno Martins on said

    Reply
    



Bruno Martins

    Hi, and how did you get into that situation? lol how do i put my asp.net(c#) change its password on the first login?

  • 



Chris

    Thanks. This was very useful for me.

  • 



Jason

    Kudos!
    After mucking around and getting this working by using passwordFormat="encryped" on my membership provider, and generating a machine key so that MembershipUser.GetPassword() will work correctly...your solution is much cleaner and does the job.

    Cheers

  • 



Black

    Thanks bro. Saved my day :)

Add a Comment (gravatar-enabled)