11

I'm currently migrating the old API that use .Net Framework 4.5.2 to .Net Core 2.1, in the old API that use .Net Framework 4.5.2 there's this script :

PasswordHasher hasher = new PasswordHasher();
password = ConfigurationManager.AppSettings["userDefaultPassword"].ToString();
hashedPassword = hasher.HashPassword(password);

so i want to know, is there any equal function that i can use in .Net Core 2.1 that produce the same hash result as in the old .Net Framework?

0

1 Answer 1

12

I believe that the equivalent is this:

IConfiguration _configuration;
PasswordHasher<User> hasher = new PasswordHasher<User>(
    new OptionsWrapper<PasswordHasherOptions>(
        new PasswordHasherOptions() {
            CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2
    })
);
password = _configuration["userDefaultPassword"].ToString();
hashedPassword = hasher.HashPassword(user, password);

Notes:

  • You should now use IConfiguration (Configuration in Startup.cs) rather than ConfigurationManager.
  • PasswordHasher now takes your user object as a generic parameter (and an instance when calling HashPassword).
  • I've specified CompatibilityMode for IdentityV2 since it sounds like you want to generate backwards-compatible password hashes (i.e. you can access the database from .NET Framework and understand the hashes generated by .NET Core). If this isn't the case, you can remove it since the verification code can verify older hashes without setting this.
  • OptionsWrapper is under the Microsoft.Extensions.Options namespace.
Sign up to request clarification or add additional context in comments.

6 Comments

because there is "CompatiblityMode", if i deploy the API on non-windows based server will this work?
Well, CompatibilityMode is a feature of the .NET Core PasswordHasher, so I'd be very surprised (and headed straight to GitHub to report a bug) if it didn't work. Note that this is compatibility with their older hashing function (in ASP.NET Identity V2), and nothing to do with any compatibility modes that software can run on under Windows, if that's what you're thinking of?
i'm sorry, i just misunderstood the "compatibility" meaning. Now after i try your code, i got this error "cannot convert from Microsoft.AspNetCore.Indentity.PasswordHasherOption to Microsoft.Extensions.Options.IOptions<Microsoft.AspNetCore.Indentity.PasswordHasherOption>"
My bad, I missed something out. Try with the updated code. :-)
What's the point of providing user to the password hasher? I checked verifying my hashes and they only fail of I alter the stored hash and/or provided password. Horsing around with the user name seems not to bug the verification algorithm. What do I miss?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.