How to use MembershipValidatePasswordEventHandler?

2019-05-26 16:20发布

问题:

Is there any way to put some restriction on password selection while creating new user with asp. net Membership.??
Condition Like
Password strength:

  • Minimum of 8 characters, with character complexity enforced. ie: Not contain the user's account name
  • Be at least eight characters in length
  • Contain characters from three of the following four categories:

English uppercase characters (A through Z)
English lowercase characters (a through z)
Base 10 digits (0 through 9)
Non-alphabetic characters (for example, !, $, #, %)

回答1:

In this case, you need to make some modifications to your Web.config. Find the following section and change it accordingly

<membership>
  <providers>
    <clear/>
    <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
         enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
         maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
         applicationName="/" />
  </providers>
</membership>

UPDATED

First, update your membership config section in web.config like following

  <membership>
  <providers>
    <clear/>
    <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
         enablePasswordRetrieval="false" enablePasswordReset="true" passwordAttemptWindow="10"
         applicationName="/" />
  </providers>
</membership>

Then, In your Account Controller, replace your Registration action(the one decorated with [HttpPost]) with the following code

[HttpPost]
public ActionResult Register(RegisterModel model)
{
    Membership.ValidatingPassword += new MembershipValidatePasswordEventHandler(OnValidatePassword);
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        MembershipCreateStatus createStatus;
        Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

        if (createStatus == MembershipCreateStatus.Success)
        {
            FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            ModelState.AddModelError("", ErrorCodeToString(createStatus));
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
 }

And finally add the code for OnValidatePassword below the Registration Action

public void OnValidatePassword(object sender,
                          ValidatePasswordEventArgs args)
{
    System.Text.RegularExpressions.Regex r =
          new System.Text.RegularExpressions.Regex(@"(?=.{8,})(?=(.*\d){1,})(?=(.*\W){1,})");

    if (!r.IsMatch(args.Password))
    {
        args.FailureInformation =
              new HttpException("Password must be at least 8 characters long and " +
                                "contain at least one number and one special character.");
        args.Cancel = true;
    }
}

Hope this can help you achieve what you want !!