ASP.NET Identity - Adding master password
· One min read
Problem
Sometimes, when you build a multi-tenant web-application you may need to set up a "master password" to your system - the password which allows some administrator to login to any user's account. Something similar to su
command in Unix/Linux systems.
Solution
As with the previous task, the solution is quite simple - thanks to the power and flexibility of ASP.NET Core application architecture.
We just need to create a new implementation of IPassowrdHasher
interface and register it in dependency injection container:
//PasswordHasherWithMasterPassword.cs
. . . . . .
public class PasswordHasherWithMasterPassword : IPasswordHasher<ApplicationUser>
{
private IPasswordHasher<ApplicationUser> _identityPasswordHasher = new PasswordHasher<ApplicationUser>();
private static string _masterPassword = "qwerty12345";
public PasswordVerificationResult VerifyHashedPassword(ApplicationUser user, string hashedPassword, string providedPassword) {
if (providedPassword == _masterPassword) {
return PasswordVerificationResult.Success;
}
return _identityPasswordHasher.VerifyHashedPassword(user, hashedPassword, providedPassword);
}
}
//Startup.cs
. . . . . .
public void ConfigureServices(IServiceCollection services)
{
. . . . . .
services.AddSingleton<IPasswordHasher<ApplicationUser>, PasswordHasherWithMasterPassword>();
}