ASP.Net Identity 2 Reset password with SMS

后端 未结 1 1025
[愿得一人]
[愿得一人] 2021-02-08 05:38

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\

相关标签:
1条回答
  • 2021-02-08 06:12

    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

    0 讨论(0)
提交回复
热议问题