kindohm
kindohm

Reputation: 1600

how to get Identity PasswordOptions in ASP.NET MVC controller

I want to read the Identity PasswordOptions that are configured in Startup.cs from an MVC Controller. My PasswordOptions is configured like this:

services.AddIdentity<ApplicationUser, IdentityRole>(config => {
        config.Password.RequireDigit = true;
        config.Password.RequiredLength = 8;
        config.Password.RequireNonAlphanumeric = true;
});

How do I then read the RequireDigit, PasswordLength, and RequireNonAlphanumeric properties in a Controller or elsewhere in the app?

Using ASP.NET Core 1.0.1.

Upvotes: 5

Views: 2095

Answers (1)

Sam FarajpourGhamari
Sam FarajpourGhamari

Reputation: 14741

Simply inject IOptions<IdentityOptions> interface to any class or controller's constructor like this:

 public class MyController : Controller
 {
     private readonly IOptions<IdentityOptions> _identityOptions;
     public MyContoller(IOptions<IdentityOptions> identityOptions)
     {
         _identityOptions=identityOptions?.Value ?? new IdentityOptions();         
     }

     public MyAction()
     {
         var length=_identityOptions.Value.Password.RequiredLength;
     }
 }

Upvotes: 15

Related Questions