Here’s a step-by-step guide on how to implement email verification for user registration in ASP.NET MVC:
1. Create the Registration Form
Create a view for the registration form where users can enter their details like name, email, password, etc. Use data annotations to add validation rules to the form fields.
xml
@model RegisterViewModel
@using (Html.BeginForm(“Register”, “Account”, FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class=”form-group”>
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email, new { @class = “form-control” })
@Html.ValidationMessageFor(m => m.Email)
</div>
// Other form fields
<button type=”submit” class=”btn btn-primary”>Register</button>
}
2. Generate a Verification Token
When a user submits the registration form, generate a unique verification token that will be sent to the user’s email. You can use a GUID or a combination of user details and a timestamp to generate the token.
csharp
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// Generate a verification token
var verificationToken = GenerateVerificationToken(user);
// Send the verification email
await SendVerificationEmail(user.Email, verificationToken);
return RedirectToAction(“VerifyEmail”);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
private string GenerateVerificationToken(ApplicationUser user)
{
// Generate a unique token using a GUID or a combination of user details and a timestamp
return Guid.NewGuid().ToString();
}
3. Send the Verification Email
Create a method to send the verification email to the user. Include the generated token in the email body or as a query parameter in the verification link.
csharp
private async Task SendVerificationEmail(string email, string verificationToken)
{
var verificationLink = Url.Action(“VerifyEmail”, “Account”, new { token = verificationToken }, Request.Url.Scheme);
var message = new MailMessage
{
From = new MailAddress(“your-email@example.com”),
To = { new MailAddress(email) },
Subject = “Verify your email”,
Body = $”Please verify your email by clicking this link: {verificationLink}”
};
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(message);
}
}
4. Verify the Email
Create an action method to handle the email verification process. Extract the token from the request and verify if it matches the token stored in the database for the user.
csharp
public async Task<ActionResult> VerifyEmail(string token)
{
var user = await UserManager.FindByEmailAsync(User.Identity.Name);
if (user != null && user.EmailConfirmed == false)
{
// Verify the token
if (IsValidVerificationToken(user, token))
{
// Mark the user as email confirmed
user.EmailConfirmed = true;
await UserManager.UpdateAsync(user);
return View(“VerifyEmailSuccess”);
}
}
return View(“VerifyEmailFailure”);
}
private bool IsValidVerificationToken(ApplicationUser user, string token)
{
// Compare the provided token with the stored token for the user
// Return true if the tokens match, false otherwise
}
5. Restrict Access Until Email is Verified
To prevent users from logging in until their email is verified, modify the login logic to check if the user’s email is confirmed before allowing access.
csharp
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByEmailAsync(model.Email);
if (user != null && await UserManager.CheckPasswordAsync(user, model.Password))
{
if (user.EmailConfirmed)
{
// Allow login if email is confirmed
await SignInManager.SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
// Display an error message if email is not confirmed
ModelState.AddModelError(“”, “Please verify your email before logging in.”);
}
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError(“”, “Invalid login attempt.”);
}
return View(model);
}
Follow these instructions to implement email verification for user registration in ASP.NET MVC. Remember to address edge circumstances, such as resending verification emails or dealing with expired tokens, to improve the customer experience.