Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Identity 2 Reset password with SMS

I'm looking to send the user an SMS when reseting their password. I already have the facilities to send a SMS, I just need a guide on how to set it up with Identity 2.0. I can't seem to find any useful info online, the reference code itself isn't properly commented either.

I want to generate a security code, send it to the user, he must then input it into a form and then be allowed to reset his/her password. Can anyone direct me to a guide/tutorial that explains this process?

like image 886
Swifty Avatar asked Jun 02 '14 08:06

Swifty


1 Answers

After digging in the identity source code i found an alternative token provider that can generate tokens similar to phone number confirmation (six digits).

I had to implement two methods in my UserManager to generate the code and then to validate it.

I declared the token provider inside the UserManager

private TotpSecurityStampBasedTokenProvider<User, string> smsResetTokenProvider = new TotpSecurityStampBasedTokenProvider<User, string>();

This is the first method to generate the code:

public async Task<string> GenerateSMSPasswordResetToken(string userId)
    {
        var user = await base.FindByIdAsync(userId);
        var token = await smsResetTokenProvider.GenerateAsync("Reset Password", this, user);
        return token;
    }

This is the second method to validate the code:

public async Task<IdentityResult> SMSPasswordResetAsync(string userId, string token, string newPassword)
    {
        var user = await base.FindByIdAsync(userId);
        var valid = await smsResetTokenProvider.ValidateAsync("Reset Password", token, this, user);
        if (valid)
        {
            var passwordStore = Store as IUserPasswordStore<User, string>;

            var result = await UpdatePassword(passwordStore, user, newPassword);
            if (!result.Succeeded)
            {
                return result;
            }
            return await UpdateAsync(user);
        }
        else
        {
            return IdentityResult.Failed("InvalidToken");
        }
    }

You may need to tweak the code depending on your user manager

like image 152
Souhaieb Besbes Avatar answered Oct 20 '22 13:10

Souhaieb Besbes