Email Confirmation with ASP.NET Core Identity

In this article, You will learn about Email Confirmation with ASP.NET Core Identity. How Identity Users can confirm their email after receiving a token into their email account from the ASP.NET Core Identity application.

If you have not created your project yet you can create your ASP.NET Core 3-tier Web API Application by clicking on this link. Our ASP.NET Core App is the same that we have taught in our above-mentioned tutorial.

In this approach, we will send an email to a user after signup and the user will receive the email on the email address that user used for account creation. After confirming the email, user will be able to log in. If you have not configured any email sending protocol you can configure SMTP by following this link.

Let’s start:

First of all in the “startup.cs” class modify the Identity configuration to enable email confirmation.

services.AddIdentity<ApplicationUser, ApplicationRole>(config =>
            {
                config.SignIn.RequireConfirmedAccount = false;
                config.User.RequireUniqueEmail = true;
                config.Tokens.AuthenticatorIssuer = "JWT";

                // Add this line for Email confirmation
                config.SignIn.RequireConfirmedEmail = true;

            }).AddDefaultTokenProviders()
            .AddEntityFrameworkStores<ApplicationDbContext>();

“config.SignIn.RequireConfirmedEmail = true” this Identity function will check if the user has confirmed the email or not. if any user tries to sign in and the user has not confirmed the email it will prevent the user from signing in.

email confirmation with ASP.NET Core

To confirm user email we will send a token in the email to user when the user registers. For creating a token for email confirmation and sending it to the user we will do something like this.

public async Task<ResponseViewModel<object>> Signup(SignupViewModel user)
        {
            try
            {
                var appUser = new ApplicationUser
                {
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    Email = user.Email,
                    UserName = user.Email,
                    Active = true
                };

                var result = await _userManager.CreateAsync(appUser, user.Password);
	            await _userManager.AddToRoleAsync(appUser, "user");
              
                //for creating email confirmation token
                var token = HttpUtility.UrlEncode(await _userManager.GenerateEmailConfirmationTokenAsync(appUser));
                //creating a proper link of my API and attaching token and email
                var confirmationlink = "https://localhost:44379/api/Account/ConfirmEmailLink?token=" + token+"&email="+user.Email;

                var emailtemplate = new EmailTemplate();
                emailtemplate.Link = confirmationlink;
                emailtemplate.UserId = appUser.Id;
                //calling email service to send email
                var emailsent = _emailService.SendSmtpMail(emailtemplate);
                if (emailsent != true)
                    throw new HttpStatusException(System.Net.HttpStatusCode.InternalServerError, "Email not sent.");

               	await _context.SaveChangesAsync();
                
                return new ResponseViewModel<object>
                {
                    Status = true,
                    Message = "Signup Successfully, Please Confirm your Email",
                    StatusCode = System.Net.HttpStatusCode.OK.ToString(),
                    Data = appUser.Email
                };
            }
            catch (Exception e)
            {
                await _exceptionServices.CreateLog(e, user);
                throw e;
            }
        } 

GenerateEmailConfirmationTokenAsync(TUser) will generate a token that will be used to confirm user email. Our Base URL has our next API Url that will confirm user email. We have also attached the token and email of the user in the link so that we can get the Confirmation token and email in the query parameter in our next API. After that, I’m calling my email service to send an email.

email confirmation with ASP.NET Core

You will receive the email confirmation link like this. After clicking on this link your User Email Confirmation API will be automatically called that I have described below.

Now, let’s move to the next API for confirmation,

 public async Task<ResponseViewModel<object>> ConfirmEmail(string token, string email)
        {
            var user = await _userManager.FindByEmailAsync(email);
            var result = await _userManager.ConfirmEmailAsync(user, token);
            if (!result.Succeeded)
            {
                return new ResponseViewModel<object>
                {
                    Status = false,
                    Message = "Invalid Token",
                    StatusCode = System.Net.HttpStatusCode.Ok.ToString(),
                };
            }
            else
            {
                return new ResponseViewModel<object>
                {
                    Status = true,
                    Message = "Your Email Confirmed Succesfully",
                    StatusCode = System.Net.HttpStatusCode.OK.ToString(),
                };
            }
            
        }

ConfirmEmailAsync(user, token) will take two arguments one user and the 2nd is token. It will confirm the user token if it’s valid and return the response.

I have also written a complete tutorial on Reset Password in ASP.NET Core Identity with Email.

Conclusion:

You can configure Email Confirmation by following these simple steps that we have mentioned above. In our next post, we will tell you that how identity users reset passwords. if you face any issue or problem while configuring this method with your ASP.NET Core project feel free to comment below. We will try to respond ASAP.

Leave a Reply

Your email address will not be published.