2013-11-01 11 views
13

Provare a modificare la lunghezza minima della password predefinita su 4 caratteri. Lo so, 4 !!! Ridicolo, giusto! Non è la mia chiamata.Modificare la lunghezza della password in MVC 5 Membership

In ogni caso, l'ho modificato sul RegisterViewModel ma in realtà non lo cambia. Per illustrare ho pubblicato il codice qui sotto. ModleState.IsValid restituisce correttamente in base al ViewModel aggiornato. Tuttavia è quindi chiama UserManager.CreateAsync() che restituisce False con un messaggio di errore di "password deve essere di almeno 6 caratteri"

ho seguito la procedura in questo, molto, post simile (Change Password...), ma non funziona per MVC 5 per quanto posso dire. Restituisce ancora lo stesso messaggio.

// 
    // POST: /Account/Register 
    [HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Register(RegisterViewModel model) 
    { 
     if (ModelState.IsValid) 
     { 
      var user = new ApplicationUser() { UserName = model.UserName, LastLogin = model.LastLogin }; 


// This is where it 'fails' on the CreateAsync() call 
        var result = await UserManager.CreateAsync(user, model.Password); 
        if (result.Succeeded) 
        { 
         await SignInAsync(user, isPersistent: false); 
         return RedirectToAction("Index", "Home"); 
        } 
        else 
        { 
         AddErrors(result); 
        } 
       } 
      // If we got this far, something failed, redisplay form 
      return View(model); 
     } 

risposta

14

Come si può vedere UserManager ha proprietà pubblica IIdentityValidator<string> PasswordValidator per la convalida della password che è attualmente inizializzata nel costruttore UserManager s' con il parametro hardcoded this.PasswordValidator = (IIdentityValidator<string>) new MinimumLengthValidator(6);.

È possibile impostare questa proprietà con l'oggetto MinimumLengthValidator con la lunghezza della password richiesta.

4

Controllare il seguente articolo a MSDN

Implementing custom password policy using ASP.NET Identity

Il suggerimento è quello di estendere la classe UserManager nell'applicazione e impostando la proprietà PasswordValidator nella contructor:

public class MyUserManager : UserManager<ApplicationUser> 
{ 
    public MyUserManager() : 
     base(new UserStore<ApplicationUser>(new ApplicationDbContext())) 
    { 
     PasswordValidator = new MinimumLengthValidator(4); 
    } 
} 

E poi nel il tuo controller (o classe base di controller) instantiate MyUserManager:

public BaseController() : this(new MyUserManager()) 
{ 
} 

public BaseController(MyUserManager userManager) 
{ 
    UserManager = userManager; 
} 

public MyUserManager UserManager { get; private set; } 

È inoltre possibile implementare un validatore personalizzato per verificare regole di password più complesse implementando IIdentityValidator e sostituendo il validatore predefinito.

9

È possibile impostare le proprietà della password utilizzando PasswordValidator disponibile nel file IdentityConfig.cs nella Directory di App_Start.

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    { 
     var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>())); 
     // Configure validation logic for usernames 
     manager.UserValidator = new UserValidator<ApplicationUser>(manager) 
     { 
      AllowOnlyAlphanumericUserNames = false, 
      RequireUniqueEmail = true 
     }; 

     // Configure validation logic for passwords 
     manager.PasswordValidator = new PasswordValidator 
     { 
      RequiredLength = 6, 
      RequireNonLetterOrDigit = false, 
      RequireDigit = true, 
      RequireLowercase = true, 
      RequireUppercase = true, 
     }; 

     // Configure user lockout defaults 
     manager.UserLockoutEnabledByDefault = true; 
     manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); 
     manager.MaxFailedAccessAttemptsBeforeLockout = 5; 

     // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user 
     // You can write your own provider and plug it in here. 
     manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser> 
     { 
      MessageFormat = "Your security code is {0}" 
     }); 
     manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser> 
     { 
      Subject = "Security Code", 
      BodyFormat = "Your security code is {0}" 
     }); 
     manager.EmailService = new EmailService(); 
     manager.SmsService = new SmsService(); 
     var dataProtectionProvider = options.DataProtectionProvider; 
     if (dataProtectionProvider != null) 
     { 
      manager.UserTokenProvider = 
       new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity")); 
     } 
     return manager; 
    }