2
votes

I am creating a small demo for reset password in web API and identity using in .net MVC c#.and I am clicking on forgot password send one code in the mail using a query string. In the mail code is correct getting. now I am going for the change password and getting the code from the URL not getting propare in the token '==' last end not getting and get error invalid token how can do fix it this error anyone knows?

this my ForgotPassword method in Account Controller :

  public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordViewModel model)
    {

        try
        {
            var user = await UserManager.FindByNameAsync(model.Email);

            if (user == null)
            {
                return Ok();
            }

            // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
            // Send an email with this link
            string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
            await UserManager.SendEmailAsync(user.Id, "Reset Password",Request.RequestUri.GetLeftPart(UriPartial.Authority) + "/home/ChangePassword?Code=" + code);
            return Ok("Ok");
        }
        catch (Exception ex)
        {
            ExceptionsLogging.SendExcepToDB(ex);
            throw new HttpException(500, ex.Message);
        }
    }

this is my ResetPasswordMethod :

  public async Task<IHttpActionResult> ResetPassword(ChangePasswordBindingModel model)
    {
        try
        {                
            var user = await UserManager.FindByNameAsync(model.Email);
            if (user == null)
            {
                // Don't reveal that the user does not exist
                return Ok();
            }
            var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.NewPassword); // here not getting code propare 
            if (result.Succeeded)
            {
                return Ok("Done");
            }
            return Ok();
        }
        catch (Exception ex)
        {
            ExceptionsLogging.SendExcepToDB(ex);
            throw new HttpException(500, ex.Message);
        }
    }

any one know how can fix it i am try encode/decode but now getting propare

1

1 Answers

3
votes

You must encode the generated token before sending the email

string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var encodedCode = HttpUtility.UrlEncode(code);
await UserManager.SendEmailAsync(user.Id, "Reset Password",Request.RequestUri.GetLeftPart(UriPartial.Authority) + "/home/ChangePassword?Code=" + encodedCode);
return Ok("Ok");