Calling .NET types from PowerShell is not always as straightforward as it seems. Here’s how I was able to use the PasswordHasher to generate a hash compatible with ASP.NET Core Identity’s AspNetUsers table.
First, gather the NuGet package for Microsoft.Extensions.Identity.Core and all of its dependencies.
- Microsoft.Extensions.Identity.Core
- Microsoft.Extensions.Options
- Microsoft.Extensions.Logging.Abstractions
- Microsoft.Extensions.DependencyInjection.Abstractions
- Microsoft.Extensions.Primitives
- System.Memory
Pick a runtime and gather the DLLs into a folder called “References” under the folder with your PowerShell script. I chose net461 but it depends on your platform.
Here’s the function to get a password hash:
|
|
The constructor for PasswordHasher
defaults the options to null
. However,
PowerShell kept complaining it couldn’t find a constructor. So the code creates
a PasswordHasherOptions
instance and calls
Options.Create.
Also note that the generic for PasswordHasher
is string
. This is the type
of the user. A brief look at
the code
shows that the default implementation doesn’t use the user type/object for
anything.
When it comes to adding the types, they have to be added in the right order. PowerShell was not able to automatically pull in other assemblies in the same path based on dependencies.
If you’re using Visual Studio Code, it may suggest using SecureString
for the
Password parameter.
The .NET SecureString is being retired though.