Course contentsShow
← C#
Lesson 1183 of 1,90811. Identity, Security, and ClaimsFree lesson

Email Confirmation and Account Validation

Implement user account lifecycle management including mandatory email verification.

In this lesson, you will learn how to enforce account verification by requiring users to prove ownership of their email address before they can fully access your application.

The Lifecycle of an Unverified Account

When a user registers, you shouldn’t consider their account "active" immediately. If you allow unrestricted access, you risk spam signups or account takeovers. Instead, you change the account status to "unconfirmed." In ASP.NET Core Identity, this is typically handled by checking the EmailConfirmed property on your ApplicationUser.

The workflow follows three steps:

  1. Registration: Create the user, but don't log them in yet. Generate a secure token using UserManager.GenerateEmailConfirmationTokenAsync(user).
  2. Notification: Send this token to the user’s email, usually embedded in a URL (e.g., https://yourapp.com/confirm?userId=123&token=ABC).
  3. Validation: When the user clicks the link, your controller uses UserManager.ConfirmEmailAsync(user, token). If successful, you flip the EmailConfirmed flag to true.

Protecting Access

To enforce this, you must check the user's status within your authentication logic or via a custom requirement. A simple way to block unverified users is during the login process:

var user = await _userManager.FindByEmailAsync(model.Email);
if (user != null && !await _userManager.IsEmailConfirmedAsync(user))
{
    // Redirect to a "Resend Confirmation" page or show an error
    ModelState.AddModelError(string.Empty, "Please confirm your email before logging in.");
    return View();
}

By ensuring that EmailConfirmed is checked at the entry point, you prevent unauthorized users from interacting with your system. You can also implement a custom AuthorizationHandler if you want to restrict specific parts of your application based on this flag, rather than just the login process itself.

Remember, the goal is not just to collect an email, but to ensure the identity provided is valid and reachable. Always keep your confirmation tokens short-lived to prevent potential reuse of leaked links.

Key Takeaway: Never consider an identity fully trusted until the email ownership has been cryptographically verified via a secure, one-time token flow.