使用 VS2015 建立 ASP.NET MVC 5 專案(含 Individual User Accounts),註冊頁面提示:
Passwords must have at least one non letter or digit character.
Passwords must have at least one lowercase ('a'-'z').
Passwords must have at least one uppercase ('A'-'Z').
但 RegisterViewModel.Password 僅有 [StringLength(100, MinimumLength=6)],未見複雜度屬性。密碼規則在哪設定?
ASP.NET Identity 預設於 App_Start/IdentityConfig.cs 內 ApplicationUserManager.Create 方法中配置:
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true, // 至少一個非字母數字
RequireDigit = true, // 至少一個數字
RequireLowercase = true, // 至少一個小寫
RequireUppercase = true // 至少一個大寫
};
App_Start/IdentityConfig.cs。ApplicationUserManager.Create 方法。PasswordValidator 屬性,例如:manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 8,
RequireNonLetterOrDigit = false, // 允許純字母數字
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = false // 不強制大寫
};
若需更複雜規則(如禁止常見密碼、檢查歷史密碼),可自行實作:
public class CustomPasswordValidator : IIdentityValidator<string>
{
public async Task<IdentityResult> ValidateAsync(string item)
{
var errors = new List<string>();
if (item.Length < 8) errors.Add("密碼至少 8 碼");
if (!Regex.IsMatch(item, @"\d")) errors.Add("需包含數字");
if (!Regex.IsMatch(item, @"[a-z]")) errors.Add("需包含小寫");
if (await IsCommonPassword(item)) errors.Add("密碼過於常見");
return errors.Any() ? IdentityResult.Failed(errors.ToArray()) : IdentityResult.Success;
}
// 輔助方法...
}
然後註冊:manager.PasswordValidator = new CustomPasswordValidator();
UserManager.CreateAsync(user, password)UserManager.ChangePasswordAsync(...)UserManager.ResetPasswordAsync(...)前端 RegisterViewModel 的 DataAnnotations 僅供客戶端驗證(jQuery Validate),真正強制執行的是後端 PasswordValidator。
RegisterViewModel 的 [RegularExpression] 即可 → 僅影響前端提示,後端仍依 PasswordValidator。manager.UserLockoutEnabledByDefault = true; 等設定同在 IdentityConfig.cs。