Reputation: 11
I try to generate an Email confirmation token, I successfully generate it and the put it in the link alongside with the user id that I send to the registered user. The email arrives, and when I hover my mouse over it the link shows the "right way".
And when I click on it, I get the following error:
I tried a few different way, but I can't make it work. My code is below:
[HttpPost]
public async Task<IActionResult> SignUp(RegisterViewModel model)
{
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await _userManager.AddToRoleAsync(user, "User");
var confirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var confirmationLink = $"https://localhost:44314/Account/VerifyEmail?userId={user.Id}&confirmationToken={confirmationToken}";
MailMessage mailMessage = new MailMessage
(
new MailAddress(_configuration.GetValue<string>("Smtp:From"),
_configuration.GetValue<string>("Smtp:Username")),
new MailAddress(model.Email)
);
mailMessage.Subject = _configuration.GetValue<string>("Smtp:ConfirmRegister");
mailMessage.Body = $"<a href=\"{confirmationLink}\">Verify Email</a>";
mailMessage.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = _configuration.GetValue<string>("Smtp:Server");
smtp.Port = _configuration.GetValue<int>("Smtp:Port");
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential();
networkCredential.UserName = _configuration.GetValue<string>("Smtp:From");
networkCredential.Password = _configuration.GetValue<string>("Smtp:Password");
smtp.UseDefaultCredentials = false;
smtp.Credentials = networkCredential;
smtp.Send(mailMessage);
return RedirectToAction("Index", "Home");
}
foreach (var error in result.Errors)
{
_toastNotification.AddErrorToastMessage(error.Description, new ToastrOptions()
{
Title = "Ooops!"
});
ModelState.AddModelError(string.Empty, error.Description);
}
return View(model);
}
public async Task<IActionResult> VerifyEmail(string userId, string confirmationToken)
{
var user = await _userManager.FindByIdAsync(userId);
if (user == null) _toastNotification.AddErrorToastMessage("Error");
var result = await _userManager.ConfirmEmailAsync(user, confirmationToken);
if (result.Succeeded)
{
return View();
}
return BadRequest();
}
Upvotes: 0
Views: 199
Reputation: 11
I found a solution here: Invalid Token. while verifying email verification code using UserManager.ConfirmEmailAsync(user.Id, code)
To make it work, I just had to encode the token:
HttpUtility.UrlEncode(tokenGoesHere);
Upvotes: 1