Search code examples
c#asp.net-mvcasp.net-coreasp.net-identityasp.net-core-2.1

How to reuse identity password validation when changing passwords


I'm developing an asp.net core 2.1 project using Identity (UserManager, RoleManager), whose password settings are:

services.Configure<IdentityOptions>(options =>
    {
        options.Lockout.AllowedForNewUsers = false;
        options.Lockout.MaxFailedAccessAttempts = 3;
        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
        options.Password.RequireDigit = true;
        options.Password.RequireLowercase = true;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequireUppercase = true;
        options.Password.RequiredLength = 6;
        options.Password.RequiredUniqueChars = 1;
        options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    });

I'm developing my own change password functionality but I would like to know if there is a way to take advantage of previous password settings (before mentioned Startup settings) to validate new password (eg: by injecting a service), avoiding to create a new password validator or maybe UserManager provides a way to validate?


Solution

  • I've found solution by just using ChangePasswordAsync method of UserManager, it checks for passwords validation policies:

    var result = await _userManager.ChangePasswordAsync(usuario, model.ContraseñaActual, model.ContraseñaNueva);
    

    After that, checking boolean property result.Succeeded and result.Errors collection, I could validate message errors according validation policy.

    Also thanks to Tao Zhou for the alternative help