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.
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.
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.
Customizing the email confirmation process
While ASP.NET Core Identity offers email confirmation out of the box, you might want to customize the email to make it more personalized or to match your application’s design.
To customize the confirmation email template, you can use the EmailSender
service provided by ASP.NET Core Identity. This service sends the confirmation email to the user’s email address. You can override the default email template by creating a new email view file and using it to replace the default view.
Here are the steps to customize the email confirmation process:
- Create a new email view file: To create a new email view file, right-click on your project in Visual Studio and select “Add” -> “New Item”. Then, select “Razor View” from the list of templates and give it a name like “ConfirmationEmail.cshtml”. In this file, you can add HTML code for the email body and use the
@Model
variable to display dynamic data such as the user’s name or confirmation link. - Override the default email template: After creating the new email view file, you need to tell ASP.NET Core Identity to use this file instead of the default template. To do this, add the following code to the
ConfigureServices
method in yourStartup.cs
file:
services.AddTransient();
services.Configure(options =>
{
options.ViewName = “ConfirmationEmail”;
});
This code registers the EmailSender
service and sets the ViewName
property to the name of your new email view file.
- Add custom tokens to the confirmation email: If you want to add custom tokens to the confirmation email, such as the user’s email address or a timestamp, you can use the
TokenProvider
class provided by ASP.NET Core Identity. This class generates a unique token for each confirmation email and includes it in the confirmation link. You can override the default token provider to generate custom tokens. - Modify the confirmation link URL: By default, the confirmation link in the email points to the built-in confirmation endpoint in ASP.NET Core Identity. If you want to customize this URL or add query parameters, you can do so by creating a custom
IUserConfirmationEndpointService
and registering it in yourStartup.cs
file.
Handling email confirmation
After the confirmation email has been sent to the user, they will need to verify their email address by clicking on the confirmation link. Here’s how you can handle email confirmation in your ASP.NET Core Identity application:
Verifying the email address
When the user clicks on the confirmation link, they will be directed to the built-in confirmation endpoint in ASP.NET Core Identity. This endpoint verifies the email address and updates the user’s status to “confirmed”. If the email address is already confirmed or the confirmation link is invalid, the endpoint will return an error.
Redirection after email confirmation
After the email address has been confirmed, you might want to redirect the user to a different page, such as the login page or a custom “Welcome” page. To do this, you can use the SignInManager
service provided by ASP.NET Core Identity. This service signs the user in and sets the authentication cookie, allowing the user to access protected pages.
For example, you can add the following code to the confirmation endpoint to sign in the user and redirect them to the login page:
var result = await _userManager.ConfirmEmailAsync(user, code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(“Login”, “Account”);
}
This code confirms the email address using the ConfirmEmailAsync
method, signs the user in using the SignInAsync
method, and redirects them to the login page using the RedirectToAction
method.
Handling errors during confirmation
If the email address is already confirmed or the confirmation link is invalid, the confirmation endpoint will return an error. To handle these errors, you can customize the error message and redirect the user to a different page.
For example, you can add the following code to the confirmation endpoint to display a custom error message and redirect the user to the home page:
var result = await _userManager.ConfirmEmailAsync(user, code);
if (result.Succeeded)
{
// email confirmed successfully
return View(“EmailConfirmed”);
}
else
{
// error during confirmation
ModelState.AddModelError(string.Empty, “Email confirmation failed.”);
return RedirectToAction(“Index”, “Home”);
}
This code displays a custom error message using the AddModelError
method and redirects the user to the home page using the RedirectToAction
method.
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.