Search code examples
asp.netvalidationemailasp.net-identityasp.net-identity-3

Checking password complexity and validity of a token during email confirmation on Identity 3.0


I have a web app, using ASP.NET Identity 3.0, in which I create the users (instead of users registering themselves). I send a confirmation email to validate their email accounts. The idea is that they come in through the URL and, since they don't have a password set yet, they will set an initial password and validate their email in one fell swoop (I'm trying to kill two birds with one stone as elegantly as possible).

The problem is that I shouldn't confirm the email with UserManager.ConfirmEmail() if the password they entered isn't a valid password as per the complexity policy because this will expire the token. The only way I know to check if a password complies is to actually try to set it with UserManager.AddPassword() but I shouldn't try to change it unless I know the email confirmation token is valid.

How can I check if a password will be compliant without setting it? Or how can I check if a token is valid without expiring it?


Solution

  • ASP.NET Identity 3.0 does provide a password validator that you could use to check if a password is valid before taking other steps.

    Here is where you can find the actual code.

    Here is where you can find some unit tests that will give you an idea of how to use the password validator.

    The general usage looks like this:

    var validator = new PasswordValidator<User>();
    var result = await validator.ValidateAsync(UserManager, null, passwordToValidate);
    if (result.Failed) // Failed Validation
    if (result.Succeeded) // Passed Validation
    

    The 2nd parameter to ValidateAsync is the User instance, but that may not be applicable in your situation, so it is null here.

    I hope this helps you out.