Search code examples
c#asp.net-coredependency-injectionasp.net-core-mvcasp.net-core-identity

Access Identity Password Options after Configure Services


In the ConfigureServices startup method, during configuration of the Identity service, the password rules can be configured using code as follows:

services.Configure<IdentityOptions>(options =>
{
    options.Password.RequireDigit = false;
    options.Password.RequireLowercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireUppercase = false;
    options.Password.RequiredLength = 6;
    options.Password.RequiredUniqueChars = 2;
});

Where options.Password is an Identity object called PasswordOptions. Please note my security is so lax merely to make working on the Register action a little smoother without having to deal repetitively with complex passwords.

Now in my register page, I would like to have a GeneratePassword method that takes a PasswordOptions instance as input and generates a password conforming to those options. I would like that object to have the same values as I used setting the password options in ConfigureServices.

Is there any way to access these option values? So far the only solution I have is to store the password options in my appsettings.json, as a serialized PasswordOptions and use the Options pattern to inject a PasswordOptions into my Register page's PageModel. However, I may not wish to store the options in the config file, and would like to access them later just as they are hard-coded in ConfigureServices.


Solution

  • You can just request an instance of IOptions<IdentityOptions> from DI in your method and then access it using something like the following:

    public class RegisterModel : PageModel
    {
        private readonly IdentityOptions identityOptions;
    
        public RegisterModel(IOptions<IdentityOptions> identityOptions)
        {
            this.identityOptions = identityOptions.Value;
        }
    
        public void OnGet()
        {
            identityOptions.Password.RequireDigit; // etc
        }
    }