Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AspNet Core Generate and Change Email Address

I am trying to implement a way for users to change their email in AspNetCore so on the Account Management screen I have the change function that will call GenerateChangeEmailTokenAsync on the user manager, then sends the email with the link containing the Token and UserId.

My problem is how do I allow the link the change the email address to the new address since ChangeEmailAsync requires the new email address be entered.

What is the best practice way of implementing this functionality? I do not want to send over the new email address in the email link but also do not want to make them type the email again. Hopefully someone has done this, I cannot find it anywhere only, and it should be very simple.

like image 966
Tim Scriv Avatar asked Apr 01 '16 23:04

Tim Scriv


2 Answers

I know it is late answering this, but I was looking for it myself before, and thought I leave the answer here for others.

The GenerateChangeEmailTokenAsync method takes the new email as part in the hash of the token. Next you create a link that contains the token, the new email and the old email

 var token = await _userManager.GenerateChangeEmailTokenAsync(user, model.NewEmail);
 var resetLink = Url.Action("ChangeEmailToken", "account", new {token = token, oldEmail = user.Email, newEmail = model.newEmail }, protocol: HttpContext.Request.Scheme);

Next you send this link to the user in an email.

When clicked, the user hits the method named in the link (here "ChangeEmailToken" on AccountController:

 [AllowAnonymous]
 [HttpGet]
 public async Task<IActionResult> ChangeEmailToken([FromQuery] string token, [FromQuery] string oldEmail, [FromQuery] string newEmail)

Next you need to verify the token, and -if succesful- update the email address.

var result = await _userManager.ChangeEmailAsync(user, newEmail, token);
like image 99
Pieter van Kampen Avatar answered Nov 01 '22 21:11

Pieter van Kampen


The normal flow is to let the user update profile as usual.

If the user updated their email address then that new email address needs to be verified.

That is when you generate the token with GenerateChangeEmailTokenAsync.

You send that token as a link to the new email address.

When the user clicks the link in the new email it takes them back to you site which automatically confirms the token and verifies the new email address.

like image 3
Nkosi Avatar answered Nov 01 '22 21:11

Nkosi