"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Create a secure ASP.NET MVC 5 web app with log in, email confirmation and password reset (C#)

by Rick Anderson

This tutorial shows you how to build an ASP.NET MVC 5 web app with email confirmation and password reset using the ASP.NET Identity membership system. You can download the completed application here. The download contains debugging helpers that let you test email confirmation and SMS without setting up an email or SMS provider.

This tutorial was written by Rick Anderson ( Twitter: [@RickAndMSFT](https://twitter.com/RickAndMSFT) ).

## Create an ASP.NET MVC app

Start by installing and running Visual Studio Express 2013 for Web or Visual Studio 2013. Install Visual Studio 2013 Update 3 or higher.

[!NOTE] Warning: You must install Visual Studio 2013 Update 3 or higher to complete this tutorial.

  1. Create a new ASP.NET Web project and select the MVC template. Web Forms also supports ASP.NET Identity, so you could follow similar steps in a web forms app.
  2. Leave the default authentication as Individual User Accounts. If you’d like to host the app in Azure, leave the check box checked. Later in the tutorial we will deploy to Azure. You can open an Azure account for free.
  3. Set the project to use SSL.
  4. Run the app, click the Register link and register a user. At this point, the only validation on the email is with the [EmailAddress] attribute.
  5. In Server Explorer, navigate to **Data Connections*, right click and select Open table definition.

    The following image shows the AspNetUsers schema:

  6. Right click on the AspNetUsers table and select Show Table Data.

    At this point the email has not been confirmed.
  7. Click on the row and select delete. You’ll add this email again in the next step, and send a confirmation email.

Email confirmation

It’s a best practice to confirm the email of a new user registration to verify they are not impersonating someone else (that is, they haven’t registered with someone else’s email). Suppose you had a discussion forum, you would want to prevent "bob@example.com" from registering as "joe@contoso.com". Without email confirmation, "joe@contoso.com" could get unwanted email from your app. Suppose Bob accidently registered as "bib@example.com" and hadn’t noticed it, he wouldn’t be able to use password recover because the app doesn’t have his correct email. Email confirmation provides only limited protection from bots and doesn’t provide protection from determined spammers, they have many working email aliases they can use to register.

You generally want to prevent new users from posting any data to your web site before they have been confirmed by email, a SMS text message or another mechanism. In the sections below, we will enable email confirmation and modify the code to prevent newly registered users from logging in until their email has been confirmed.

## Hook up SendGrid

Although this tutorial only shows how to add email notification through SendGrid, you can send email using SMTP and other mechanisms (see additional resources).

  1. In the Package Manager Console, enter the following the following command:

    [!code-consoleMain]
       1:  Install-Package SendGrid
  2. Go to the Azure SendGrid sign up page and register for free SendGrid account. Add code similar to the following to configure SendGrid:

    [!code-csharpMain]

       1:  public class EmailService : IIdentityMessageService
       2:  {
       3:     public async Task SendAsync(IdentityMessage message)
       4:     {
       5:        await configSendGridasync(message);
       6:     }
       7:   
       8:     // Use NuGet to install SendGrid (Basic C# client lib) 
       9:     private async Task configSendGridasync(IdentityMessage message)
      10:     {
      11:        var myMessage = new SendGridMessage();
      12:        myMessage.AddTo(message.Destination);
      13:        myMessage.From = new System.Net.Mail.MailAddress(
      14:                            "Joe@contoso.com", "Joe S.");
      15:        myMessage.Subject = message.Subject;
      16:        myMessage.Text = message.Body;
      17:        myMessage.Html = message.Body;
      18:   
      19:        var credentials = new NetworkCredential(
      20:                   ConfigurationManager.AppSettings["mailAccount"],
      21:                   ConfigurationManager.AppSettings["mailPassword"]
      22:                   );
      23:   
      24:        // Create a Web transport for sending email.
      25:        var transportWeb = new Web(credentials);
      26:   
      27:        // Send the email.
      28:        if (transportWeb != null)
      29:        {
      30:           await transportWeb.DeliverAsync(myMessage);
      31:        }
      32:        else
      33:        {
      34:           Trace.TraceError("Failed to create Web transport.");
      35:           await Task.FromResult(0);
      36:        }
      37:     }
      38:  }

You’ll need to add the following includes:

[!code-csharpMain]

   1:  using SendGrid;
   2:  using System.Net;
   3:  using System.Configuration;
   4:  using System.Diagnostics;

To keep this sample simple, we’ll store the app settings in the web.config file:

[!code-xmlMain]

   1:  </connectionStrings>
   2:     <appSettings>
   3:        <add key="webpages:Version" value="3.0.0.0" />
   4:        <!-- Markup removed for clarity. -->
   5:        
   6:        <add key="mailAccount" value="xyz" />
   7:        <add key="mailPassword" value="password" />
   8:     </appSettings>
   9:    <system.web>

[!WARNING] Security - Never store sensitive data in your source code. The account and credentials are stored in the appSetting. On Azure, you can securely store these values on the Configure tab in the Azure portal. See Best practices for deploying passwords and other sensitive data to ASP.NET and Azure.

Enable email confirmation in the Account controller

[!code-csharpMain]

   1:  //
   2:  // POST: /Account/Register
   3:  [HttpPost]
   4:  [AllowAnonymous]
   5:  [ValidateAntiForgeryToken]
   6:  public async Task<ActionResult> Register(RegisterViewModel model)
   7:  {
   8:      if (ModelState.IsValid)
   9:      {
  10:          var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
  11:          var result = await UserManager.CreateAsync(user, model.Password);
  12:          if (result.Succeeded)
  13:          {
  14:              await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
  15:   
  16:              string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
  17:              var callbackUrl = Url.Action("ConfirmEmail", "Account", 
  18:                 new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
  19:              await UserManager.SendEmailAsync(user.Id, 
  20:                 "Confirm your account", "Please confirm your account by clicking <a href=\"" 
  21:                 + callbackUrl + "\">here</a>");
  22:   
  23:              return RedirectToAction("Index", "Home");
  24:          }
  25:          AddErrors(result);
  26:      }
  27:   
  28:      // If we got this far, something failed, redisplay form
  29:      return View(model);
  30:  }

Verify the Views.cshtml file has correct razor syntax. ( The @ character in the first line might be missing. )

[!code-cshtmlMain]

   1:  @{
   2:      ViewBag.Title = "Confirm Email";
   3:  }
   4:   
   5:  <h2>@ViewBag.Title.</h2>
   6:  <div>
   7:      <p>
   8:          Thank you for confirming your email. Please @Html.ActionLink("Click here to Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })
   9:      </p>
  10:  </div>

Run the app and click the Register link. Once you submit the registration form, you are logged in.

Check your email account and click on the link to confirm your email.

## Require email confirmation before log in

Currently once a user completes the registration form, they are logged in. You generally want to confirm their email before logging them in. In the section below, we will modify the code to require new users to have a confirmed email before they are logged in (authenticated). Update the HttpPost Register method with the following highlighted changes:

[!code-csharpMain]

   1:  //
   2:  // POST: /Account/Register
   3:  [HttpPost]
   4:  [AllowAnonymous]
   5:  [ValidateAntiForgeryToken]
   6:  public async Task<ActionResult> Register(RegisterViewModel model)
   7:  {
   8:     if (ModelState.IsValid)
   9:     {
  10:        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
  11:        var result = await UserManager.CreateAsync(user, model.Password);
  12:        if (result.Succeeded)
  13:        {
  14:           //  Comment the following line to prevent log in until the user is confirmed.
  15:           //  await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
  16:   
  17:           string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
  18:           var callbackUrl = Url.Action("ConfirmEmail", "Account",
  19:              new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
  20:           await UserManager.SendEmailAsync(user.Id, "Confirm your account",
  21:              "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
  22:   
  23:           // Uncomment to debug locally 
  24:           // TempData["ViewBagLink"] = callbackUrl;
  25:   
  26:           ViewBag.Message = "Check your email and confirm your account, you must be confirmed "
  27:                           + "before you can log in.";
  28:   
  29:           return View("Info");
  30:           //return RedirectToAction("Index", "Home");
  31:        }
  32:        AddErrors(result);
  33:     }
  34:   
  35:     // If we got this far, something failed, redisplay form
  36:     return View(model);
  37:  }

By commenting out the SignInAsync method, the user will not be signed in by the registration. The TempData["ViewBagLink"] = callbackUrl; line can be used to debug the app and test registration without sending email. ViewBag.Message is used to display the confirm instructions. The download sample contains code to test email confirmation without setting up email, and can also be used to debug the application.

Create a Views\Shared\Info.cshtml file and add the following razor markup:

[!code-cshtmlMain]

   1:  @{
   2:     ViewBag.Title = "Info";
   3:  }
   4:  <h2>@ViewBag.Title.</h2>
   5:  <h3>@ViewBag.Message</h3>

Add the Authorize attribute to the Contact action method of the Home controller. You can use click on the Contact link to verify anonymous users don’t have access and authenticated users do have access.

[!code-csharpMain]

   1:  [Authorize]
   2:  public ActionResult Contact()
   3:  {
   4:     ViewBag.Message = "Your contact page.";
   5:   
   6:     return View();
   7:  }

You must also update the HttpPost Login action method:

[!code-csharpMain]

   1:  //
   2:  // POST: /Account/Login
   3:  [HttpPost]
   4:  [AllowAnonymous]
   5:  [ValidateAntiForgeryToken]
   6:  public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
   7:  {
   8:      if (!ModelState.IsValid)
   9:      {
  10:          return View(model);
  11:      }
  12:   
  13:      // Require the user to have a confirmed email before they can log on.
  14:      var user = await UserManager.FindByNameAsync(model.Email);
  15:      if (user != null)
  16:      {
  17:         if (!await UserManager.IsEmailConfirmedAsync(user.Id))
  18:         {
  19:            ViewBag.errorMessage = "You must have a confirmed email to log on.";
  20:            return View("Error");
  21:         }
  22:      }
  23:   
  24:      // This doesn't count login failures towards account lockout
  25:      // To enable password failures to trigger account lockout, change to shouldLockout: true
  26:      var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
  27:      switch (result)
  28:      {
  29:          case SignInStatus.Success:
  30:              return RedirectToLocal(returnUrl);
  31:          case SignInStatus.LockedOut:
  32:              return View("Lockout");
  33:          case SignInStatus.RequiresVerification:
  34:              return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
  35:          case SignInStatus.Failure:
  36:          default:
  37:              ModelState.AddModelError("", "Invalid login attempt.");
  38:              return View(model);
  39:      }
  40:  }

Update the Views.cshtml view to display the error message:

[!code-cshtmlMain]

   1:  @model System.Web.Mvc.HandleErrorInfo
   2:   
   3:  @{
   4:      ViewBag.Title = "Error";
   5:  }
   6:   
   7:  <h1 class="text-danger">Error.</h1>
   8:  @{
   9:     if (String.IsNullOrEmpty(ViewBag.errorMessage))
  10:     {
  11:        <h2 class="text-danger">An error occurred while processing your request.</h2>
  12:     }
  13:     else
  14:     {
  15:        <h2 class="text-danger">@ViewBag.errorMessage</h2>
  16:     }
  17:  }

Delete any accounts in the AspNetUsers table that contain the email alias you wish to test with. Run the app and verify you can’t log in until you have confirmed your email address. Once you confirm your email address, click the Contact link.

## Password recovery/reset

Remove the comment characters from the HttpPost ForgotPassword action method in the account controller:

[!code-csharpMain]

   1:  //
   2:  // POST: /Account/ForgotPassword
   3:  [HttpPost]
   4:  [AllowAnonymous]
   5:  [ValidateAntiForgeryToken]
   6:  public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
   7:  {
   8:      if (ModelState.IsValid)
   9:      {
  10:          var user = await UserManager.FindByNameAsync(model.Email);
  11:          if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
  12:          {
  13:              // Don't reveal that the user does not exist or is not confirmed
  14:              return View("ForgotPasswordConfirmation");
  15:          }
  16:   
  17:          string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
  18:          var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
  19:          await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
  20:          return RedirectToAction("ForgotPasswordConfirmation", "Account");
  21:      }
  22:   
  23:      // If we got this far, something failed, redisplay form
  24:      return View(model);
  25:  }

Remove the comment characters from the ForgotPassword ActionLink in the Views.cshtml razor view file:

[!code-cshtmlMain]

   1:  @using MvcPWy.Models
   2:  @model LoginViewModel
   3:  @{
   4:     ViewBag.Title = "Log in";
   5:  }
   6:   
   7:  <h2>@ViewBag.Title.</h2>
   8:  <div class="row">
   9:     <div class="col-md-8">
  10:        <section id="loginForm">
  11:           @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
  12:           {
  13:              @Html.AntiForgeryToken()
  14:              <h4>Use a local account to log in.</h4>
  15:              <hr />
  16:              @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  17:              <div class="form-group">
  18:                 @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
  19:                 <div class="col-md-10">
  20:                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
  21:                    @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
  22:                 </div>
  23:              </div>
  24:              <div class="form-group">
  25:                 @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
  26:                 <div class="col-md-10">
  27:                    @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
  28:                    @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
  29:                 </div>
  30:              </div>
  31:              <div class="form-group">
  32:                 <div class="col-md-offset-2 col-md-10">
  33:                    <div class="checkbox">
  34:                       @Html.CheckBoxFor(m => m.RememberMe)
  35:                       @Html.LabelFor(m => m.RememberMe)
  36:                    </div>
  37:                 </div>
  38:              </div>
  39:              <div class="form-group">
  40:                 <div class="col-md-offset-2 col-md-10">
  41:                    <input type="submit" value="Log in" class="btn btn-default" />
  42:                 </div>
  43:              </div>
  44:              <p>
  45:                 @Html.ActionLink("Register as a new user", "Register")
  46:              </p>
  47:              @* Enable this once you have account confirmation enabled for password reset functionality *@
  48:              <p>
  49:                 @Html.ActionLink("Forgot your password?", "ForgotPassword")
  50:              </p>
  51:           }
  52:        </section>
  53:     </div>
  54:     <div class="col-md-4">
  55:        <section id="socialLoginForm">
  56:           @Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel { ReturnUrl = ViewBag.ReturnUrl })
  57:        </section>
  58:     </div>
  59:  </div>
  60:   
  61:  @section Scripts {
  62:     @Scripts.Render("~/bundles/jqueryval")
  63:  }

The Log in page will now show a link to reset the password.

## Resend email confirmation link

Once a user creates a new local account, they are emailed a confirmation link they are required to use before they can log on. If the user accidently deletes the confirmation email, or the email never arrives, they will need the confirmation link sent again. The following code changes show how to enable this.

Add the following helper method to the bottom of the Controllers.cs file:

[!code-csharpMain]

   1:  private async Task<string> SendEmailConfirmationTokenAsync(string userID, string subject)
   2:  {
   3:     string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID);
   4:     var callbackUrl = Url.Action("ConfirmEmail", "Account",
   5:        new { userId = userID, code = code }, protocol: Request.Url.Scheme);
   6:     await UserManager.SendEmailAsync(userID, subject,
   7:        "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
   8:   
   9:     return callbackUrl;
  10:  }

Update the Register method to use the new helper:

[!code-csharpMain]

   1:  //
   2:  // POST: /Account/Register
   3:  [HttpPost]
   4:  [AllowAnonymous]
   5:  [ValidateAntiForgeryToken]
   6:  public async Task<ActionResult> Register(RegisterViewModel model)
   7:  {
   8:     if (ModelState.IsValid)
   9:     {
  10:        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
  11:        var result = await UserManager.CreateAsync(user, model.Password);
  12:        if (result.Succeeded)
  13:        {
  14:           //  Comment the following line to prevent log in until the user is confirmed.
  15:           //  await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
  16:   
  17:           string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");
  18:   
  19:           ViewBag.Message = "Check your email and confirm your account, you must be confirmed "
  20:                           + "before you can log in.";
  21:   
  22:           return View("Info");
  23:           //return RedirectToAction("Index", "Home");
  24:        }
  25:        AddErrors(result);
  26:     }
  27:   
  28:     // If we got this far, something failed, redisplay form
  29:     return View(model);
  30:  }

Update the Login method to resend the password when if the user account has not been confirmed:

[!code-csharpMain]

   1:  //
   2:  // POST: /Account/Login
   3:  [HttpPost]
   4:  [AllowAnonymous]
   5:  [ValidateAntiForgeryToken]
   6:  public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
   7:  {
   8:     if (!ModelState.IsValid)
   9:     {
  10:        return View(model);
  11:     }
  12:   
  13:     // Require the user to have a confirmed email before they can log on.
  14:    // var user = await UserManager.FindByNameAsync(model.Email);
  15:     var user =  UserManager.Find(model.Email, model.Password);
  16:     if (user != null)
  17:     {
  18:        if (!await UserManager.IsEmailConfirmedAsync(user.Id))
  19:        {
  20:           string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account-Resend");
  21:   
  22:            // Uncomment to debug locally  
  23:            // ViewBag.Link = callbackUrl;
  24:           ViewBag.errorMessage = "You must have a confirmed email to log on. "
  25:                                + "The confirmation token has been resent to your email account.";
  26:           return View("Error");
  27:        }
  28:     }
  29:   
  30:     // This doesn't count login failures towards account lockout
  31:     // To enable password failures to trigger account lockout, change to shouldLockout: true
  32:     var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
  33:     switch (result)
  34:     {
  35:        case SignInStatus.Success:
  36:           return RedirectToLocal(returnUrl);
  37:        case SignInStatus.LockedOut:
  38:           return View("Lockout");
  39:        case SignInStatus.RequiresVerification:
  40:           return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
  41:        case SignInStatus.Failure:
  42:        default:
  43:           ModelState.AddModelError("", "Invalid login attempt.");
  44:           return View(model);
  45:     }
  46:  }

## Combine social and local login accounts

You can combine local and social accounts by clicking on your email link. In the following sequence RickAndMSFT@gmail.com is first created as a local login, but you can create the account as a social log in first, then add a local login.

Click on the Manage link. Note the 0 external (social logins) associated with this account.

Click the link to another log in service and accept the app requests. The two accounts have been combined, you will be able to log on with either account. You might want your users to add local accounts in case their social log in authentication service is down, or more likely they have lost access to their social account.

In the following image, Tom is a social log in (which you can see from the External Logins: 1 shown on the page).

Clicking on Pick a password allows you to add a local log on associated with the same account.

Email confirmation in more depth

My tutorial Account Confirmation and Password Recovery with ASP.NET Identity goes into this topic with more details.

## Debugging the app

If you don’t get an email containing the link:

To test the verification link without email, download the completed sample. The confirmation link and confirmation codes will be displayed on the page.

## Additional Resources



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset.htm
< THANKS ME>