ASP.NET Core Identity – Add Email Confirmation

In today’s age of digitalisation, you would wish to confirm that the email address entered by the user at the time of creating an account actually belongs to him. So, that verification becomes important. ASP.NET Core helps an easy way to do that.

The email verification step in ASP.NET Core Identity works in the following manner:

  • You produce an email verification token
  • Next you send an email to the user’s email address with a link that contains the user’s ID and above generated token.
  • The user clicks on the email verification link and if there is no issue it is marked verified.
  • When the user attempts a log-in to the system you next check if his email is verified or not and allow or deny the access.

ASP.NET Core Identity gives most of the functionality required to use the above steps, you need an external aide. You require a mechanism to send emails through your code. In .NET Framework , System.Net.Mail classes is used for the same. There is no direct equivalent in .NET Core. You must use some third-party NuGet packages. For the sake of our example I am going to stick with SmtpClient class from .NET Framework’s System.Net.Mail namespace.

Let’s begin!

First of all make changes in the Project.json to use .NET Framework rather than .NET Core. You can do it like this :

“frameworks”: {

“net452″: {

“frameworkAssemblies”: {

“System.Net”: “4.0.0.0”

}

}

}

Then open the AccountController and modify its Register() POST action as shown below:

[HttpPost]

[ValidateAntiForgeryToken]

public IActionResult Register(RegisterViewModel obj)

{

if (ModelState.IsValid)

{

MyIdentityUser user = new MyIdentityUser();

user.UserName = obj.UserName;

user.Email = obj.Email;

user.FullName = obj.FullName;

user.BirthDate = obj.BirthDate;

IdentityResult result = userManager.CreateAsync(user,

obj.Password).Result;

if (result.Succeeded)

{

if(!roleManager.RoleExistsAsync(“NormalUser”).Result)

{

MyIdentityRole role = new MyIdentityRole();

role.Name = “NormalUser”;

role.Description = “Perform normal operations.”;

IdentityResult roleResult =

roleManager.CreateAsync(role).Result;

if(!roleResult.Succeeded)

{

ModelState.AddModelError(“”,

“Error while creating role!”);

return View(obj);

}

}

userManager.AddToRoleAsync(user, “NormalUser”).Wait();

//send confirmation email

string confirmationToken = userManager.

GenerateEmailConfirmationTokenAsync(user).Result;

string confirmationLink = Url.Action(“ConfirmEmail”,

“Account”, new { userid = user.Id,

token = confirmationToken },

protocol: HttpContext.Request.Scheme);

SmtpClient client=new SmtpClient();

client.DeliveryMethod = SmtpDeliveryMethod.

SpecifiedPickupDirectory;

client.PickupDirectoryLocation = @”C:\Test”;

client.Send(“test@localhost”,user.Email,

“Confirm your email”,

confirmationLink);

return RedirectToAction(“Login”, “Account”);

}

}

return View(obj);

}

The code calls the GenerateEmailConfirmationTokenAsync() method of UserManager class by passing on the MyIdentityUser object. This call returns a confirmation token for that user. For verifying an email address you require a user’s Id and his confirmation token. A URL is formed using Url.Action() that points to the ConfirmEmail action of the Accountcontroller. The URL contains the user’s Id and the confirmation token in the query string.

Then the code develops a SmtpClient object and configures it such that outgoing emails are stored in the Test folder. This is done only for testing. In a real application you will need a better way like a 3rd party component. Then the code sends an email using the Send() method of SmtpClient. The from address, to address, subject and the body is marked.

The above code will create an email to be sent to the user with a URL. You can go to your C:\Test and open the email stored there in any text editor such as Notepad. A sample verification URL is given below:

http://localhost:49310/Account/

ConfirmEmail?userid=d333fcd6-ac33-4d16-b17e-ed4096a567de&token=….

For the sake of clarity the actual token is not shown above. But you can see how the query string contains “userid” and “token” values.

Clicking on this link will take the user to ConfirmEmail() action of Account controller. The ConfirmEmail() action is shown below:

public IActionResult ConfirmEmail(string userid,string token)

{

MyIdentityUser user= userManager.FindByIdAsync(userid).Result;

IdentityResult result= userManager.

ConfirmEmailAsync(user,token).Result;

if(result.Succeeded)

{

ViewBag.Message = “Email confirmed successfully!”;

return View(“Success”);

}

else

{

ViewBag.Message = “Error while confirming your email!”;

return View(“Error”);

}

}

The ConfirmEmail() action receives the user’s ID and confirmation token from the query string. Inside, the code finds the MyIdentityUser whose Id matches with the one sent through the query string. Then ConfirmEmail() method of UserManager is called to confirm the user’s email The ConfirmEmail() method requires the MyIdentityUser object and the confirmation token.

The result of ConfirmEmail() is checked and if all goes well a success view is displayed in the browser.

Here is the final step. You need to add some checking in the Login() action that checks whether a user’s email has been verified or not. So, open the Login() POST action and modify it as given below:

[HttpPost]

[ValidateAntiForgeryToken]

public IActionResult Login(LoginViewModel obj)

{

if (ModelState.IsValid)

{

var user = userManager.FindByNameAsync

(obj.UserName).Result;

if (user != null)

{

if (!userManager.IsEmailConfirmedAsync

(user).Result)

{

ModelState.AddModelError(“”,

“Email not confirmed!”);

return View(obj);

}

}

var result = loginManager.PasswordSignInAsync

(obj.UserName, obj.Password,

obj.RememberMe,false).Result;

if (result.Succeeded)

{

return RedirectToAction(“Index”, “Home”);

}

ModelState.AddModelError(“”, “Invalid login!”);

}

return View(obj);

}

If IsEmailConfirmedAsync() returns false or not verified, an error message is displayed to the user, otherwise the login process continues.

We conclude now….. Keep coding!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>