ASP.NET MVC 使用 MembershipPasswordAttribute 收紧密码要求

问题描述 投票:0回答:1

我正在努力加强网站上的密码,并想看看我是否可以使用

MembershipPassword
?我尝试在我的模型中使用下面的代码,但没有收到任何错误消息。以下是密码要求,有什么我遗漏的吗?

密码要求:

  • 10 个字符
  • 大写
  • 小写
  • 数量
  • 特殊字符

https://learn.microsoft.com/en-us/dotnet/api/system.web.security.membershippasswordattribute?view=netframework-4.8

HTML

<input data-val="true" 
       data-val-password="Your password must be 10 characters long and contain at least one symbol (!, @, #, $, %, ^, etc)." 
       data-val-password-min="10" 
       data-val-password-nonalphamin="1" 
       data-val-required="The Password field is required." 
       id="Password" name="Password" 
       style="width: 100%;" type="password" 
       data-role="textbox" aria-disabled="false" 
       class="k-input k-valid" autocomplete="off">

型号

[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
[MembershipPassword(
    MinRequiredNonAlphanumericCharacters = 1,
    MinNonAlphanumericCharactersError = "Your password needs to contain at least one symbol (!, @, #, $, %, ^, etc).",
    ErrorMessage = "Your password must be 10 characters long and contain at least one symbol (!, @, #, $, %, ^, etc).",
    MinRequiredPasswordLength = 10
)]
public string Password { get; set; }

[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
[MembershipPassword(
    MinRequiredNonAlphanumericCharacters = 1,
    MinNonAlphanumericCharactersError = "Your password needs to contain at least one symbol (!, @, #, $, %, ^, etc).",
    ErrorMessage = "Your password must be 10 characters long and contain at least one symbol (!, @, #, $, %, ^, etc).",
    MinRequiredPasswordLength = 10
)]
c# asp.net-mvc passwords data-annotations
1个回答
0
投票

MembershipPasswordAttribute
本身并不是设计用于 ASP.NET MVC 模型验证;它主要针对 ASP.NET Web 窗体。这意味着将
MembershipPasswordAttribute
直接附加到模型属性不会在 MVC 应用程序中的模型验证过程中自动强制执行约束。

您应该能够通过创建自定义验证属性来验证密码来实现所需的密码约束(灵感来自“基于配置值的.NET核心验证属性”)。

using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

public class CustomPasswordAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null) return false;

        var password = value.ToString();

        // Check length
        if (password.Length < 10) return false;

        // Check for uppercase, lowercase, numbers and special characters
        if (!Regex.IsMatch(password, @"[A-Z]") || 
            !Regex.IsMatch(password, @"[a-z]") || 
            !Regex.IsMatch(password, @"[0-9]") || 
            !Regex.IsMatch(password, @"[@$!%*?&#]"))
        {
            return false;
        }

        return true;
    }
}

然后您可以在模型中使用此属性:

[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
[CustomPassword(ErrorMessage = "Your password must meet the required criteria.")]
public string Password { get; set; }

该自定义验证属性将强制执行您指定的密码规则。

IsValid
方法包含实际的验证逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.