2016-03-11 4 views
1

Я добавил проект Web Api в свое решение VS2015, и я пытаюсь отключить некоторые из этих требований к паролю.ASP.NET MVC 5, Web Api 2 - PasswordValidator не выполняет

Например, я хотел бы получить эту ошибку при обращении к методу Register() по запросу Скрипач POST:

Passwords must have at least one non letter or digit character. 

Я добавил manager.UserValidator и manager.PasswordValidator в IdentityConfig.cs, но это не получить удар.

Вот мой IdentityConfig.cs файл:

using System.Security.Claims; 
 
using System.Threading.Tasks; 
 
using Microsoft.AspNet.Identity; 
 
using Microsoft.AspNet.Identity.EntityFramework; 
 
using Microsoft.AspNet.Identity.Owin; 
 
using Microsoft.Owin; 
 

 
namespace WorkbenchAPI.Models 
 
{ 
 
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. 
 
    public class ApplicationUser : IdentityUser 
 
    { 
 
     public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType) 
 
     { 
 
      // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
 
      var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); 
 
      // Add custom user claims here 
 

 
      // added additional validators - 03/11/2016 BM: 
 
      manager.UserValidator = new UserValidator<ApplicationUser>(manager) 
 
      { 
 
       AllowOnlyAlphanumericUserNames = false, 
 
       RequireUniqueEmail = true 
 
      }; 
 

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

 
      return userIdentity; 
 
     } 
 
    } 
 

 
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser> 
 
    { 
 
     public ApplicationDbContext() 
 
      : base("DefaultConnection", throwIfV1Schema: false) 
 
     { 
 
     } 
 
     
 
     public static ApplicationDbContext Create() 
 
     { 
 
      return new ApplicationDbContext(); 
 
     } 
 
    } 
 
}

AccountController.cs обыденно. Опять же, я добавил проект Web Api, чтобы эти контроллеры были сгенерированы.

Вот отрывок из AccountController.cs, показывая Register() метод:

using System; 
 
using System.Collections.Generic; 
 
using System.Net.Http; 
 
using System.Security.Claims; 
 
using System.Security.Cryptography; 
 
using System.Threading.Tasks; 
 
using System.Web; 
 
using System.Web.Http; 
 
using System.Web.Http.ModelBinding; 
 
using Microsoft.AspNet.Identity; 
 
using Microsoft.AspNet.Identity.EntityFramework; 
 
using Microsoft.AspNet.Identity.Owin; 
 
using Microsoft.Owin.Security; 
 
using Microsoft.Owin.Security.Cookies; 
 
using Microsoft.Owin.Security.OAuth; 
 
using WorkbenchAPI.Models; 
 
using WorkbenchAPI.Providers; 
 
using WorkbenchAPI.Results; 
 

 
namespace WorkbenchAPI.Controllers 
 
{ 
 
    [Authorize] 
 
    [RoutePrefix("api/Account")] 
 
    public class AccountController : ApiController 
 
    { 
 
     private const string LocalLoginProvider = "Local"; 
 
     private ApplicationUserManager _userManager; 
 
     
 
     public AccountController() 
 
     { 
 
     } 
 

 
     public AccountController(ApplicationUserManager userManager, 
 
      ISecureDataFormat<AuthenticationTicket> accessTokenFormat) 
 
     { 
 
      UserManager = userManager; 
 
      AccessTokenFormat = accessTokenFormat;    
 
     } 
 

 
     public ApplicationUserManager UserManager 
 
     { 
 
      get 
 
      { 
 
       return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); 
 
      } 
 
      private set 
 
      { 
 
       _userManager = value; 
 
      } 
 
     } 
 
     
 
     
 
     // POST api/Account/Register 
 
     [AllowAnonymous] 
 
     [Route("Register")] 
 
     public async Task<IHttpActionResult> Register(RegisterBindingModel model) 
 
     { 
 
      if (!ModelState.IsValid) 
 
      { 
 
       return BadRequest(ModelState); 
 
      } 
 

 
      var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; 
 

 
      IdentityResult result = await UserManager.CreateAsync(user, model.Password); 
 

 
      if (!result.Succeeded) 
 
      { 
 
       return GetErrorResult(result); 
 
      } 
 

 
      return Ok(); 
 
     } 
 

 

 
    } 
 
} 
 

 
     
 
    

А вот отрывок из `AccountBindingModel»:

public class RegisterBindingModel 
 
    { 
 
     [Required] 
 
     [Display(Name = "Email")] 
 
     public string Email { get; set; } 
 

 
     [Required] 
 
     [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 
 
     [DataType(DataType.Password)] 
 
     [Display(Name = "Password")] 
 
     public string Password { get; set; } 
 

 
     [DataType(DataType.Password)] 
 
     [Display(Name = "Confirm password")] 
 
     [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 
 
     public string ConfirmPassword { get; set; } 
 
    }

Обновлено IdentityConfig.cs

using System.Security.Claims; 
 
using System.Threading.Tasks; 
 
using Microsoft.AspNet.Identity; 
 
using Microsoft.AspNet.Identity.EntityFramework; 
 
using Microsoft.AspNet.Identity.Owin; 
 
using Microsoft.Owin; 
 

 
namespace WorkbenchAPI.Models 
 
{ 
 
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. 
 
    public class ApplicationUser : IdentityUser 
 
    { 
 
     public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType) 
 
     { 
 
      // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
 
      var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); 
 
      // Add custom user claims here 
 

 
      // added additional validators - 03/11/2016 BM: 
 
      manager.UserValidator = new UserValidator<ApplicationUser>(manager) 
 
      { 
 
       AllowOnlyAlphanumericUserNames = false, 
 
       RequireUniqueEmail = true 
 
      }; 
 

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

 
      return userIdentity; 
 
     } 
 
    } 
 

 
    public class ApplicationUserManager : UserManager<ApplicationUser> 
 
    { 
 
     public ApplicationUserManager(IUserStore<ApplicationUser> store) 
 
      : base(store) 
 
     { 
 
     } 
 

 
     public ApplicationUserManager() 
 
      : base(new UserStore<ApplicationUser>(ApplicationDbContext.Create())) 
 
     { 
 
      Initialize(); 
 
     } 
 

 
     private void Initialize() 
 
     { 
 
      // added additional validators - 03/11/2016 BM: 
 
      this.UserValidator = new UserValidator<ApplicationUser>(this) 
 
      { 
 
       AllowOnlyAlphanumericUserNames = false, 
 
       RequireUniqueEmail = true 
 
      }; 
 

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

 
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser> 
 
    { 
 
     public ApplicationDbContext() 
 
      : base("DefaultConnection", throwIfV1Schema: false) 
 
     { 
 
     } 
 
     
 
     public static ApplicationDbContext Create() 
 
     { 
 
      return new ApplicationDbContext(); 
 
     } 
 
    } 
 
}

+0

Покажите нам класс «RegisterBindingModel» – Jasen

+0

@ Jasen - сделано. посмотрите пожалуйста post. Я смотрел на это раньше, но неясно, что добавить. –

ответ

0

Эти конфигурации должны идти в инициализации ApplicationUserManager не в ApplicationUser.

public class ApplicationUserManager : UserManager<ApplicationUser> { 

    public ApplicationUserManager() 
      : base(new UserStore<ApplicationUser>(ApplicationDbContext.Create())) { 
      Initialize(); 
    } 

    private void Initialize() { 
     // added additional validators - 03/11/2016 BM: 
     this.UserValidator = new UserValidator<ApplicationUser>(this) 
     { 
      AllowOnlyAlphanumericUserNames = false, 
      RequireUniqueEmail = true 
     }; 

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

} 
+0

Я так и думал, но он все равно не попадает. Теперь я опубликую обновленный код. –

+0

Что не попало? – Nkosi

+0

@Nikos - ну, я поставил там точку останова и запустил экземпляр отладки моего проекта Web Api, думая, что я ударил бы ваш метод 'initialize' –