- Article
afterRick Anderson
This tutorial shows you how to build an ASP.NET MVC 5 web application with email verification and password reset using the ASP.NET Identity membership system.
For an updated version of this tutorial using .NET Core, seeAccount validation and password recovery in ASP.NET Core.
Create an ASP.NET MVC application
Get started by installing and runningVisual Studio Express 2013 za weborVisual Studio 2013. InstallVisual Studio 2013 Update 3or more.
Note
Warning: You must installVisual Studio 2013 Update 3or more to complete this tutorial.
Create a new ASP.NET web project and select the MVC template. Web Forms also supports ASP.NET Identity, so you can follow similar steps in a Web Forms application.
Leave the default authentication asIndividual user accounts. If you want to host the application in Azure, leave the checkbox checked. We will deploy to Azure later in the guide. You canopen an Azure account for free.
Place itproject to use SSL.
Run the application, clickRegisterconnect and register the user. At this time, the only email confirmation is s[Email address]attribute.
In Server Explorer, go toPodatkovne veze\DefaultConnection\Tables\AspNetUsers, right-click and selectDefinition of an open table.
The following picture shows
AspNetUsers
shema:(Video) ASP.NET Core MVC Login and Registration using Identity | Asp.net core tutorialRight click onAspNetUserstable and selectShow table data.
Email is not verified at this time.Click on the row and select delete. You will add this email again in the next step and send a confirmation email.
Email confirmation
It's a best practice to verify a new user's registration email to ensure they're not impersonating someone else (that is, they didn't sign up with someone else's email). Suppose you had a discussion forum, you want to prevent"bob@example.com"
from registration as"joe@contoso.com"
. Without email confirmation,"joe@contoso.com"
may receive spam from your application. Suppose Bob accidentally registers as"bib@example.com"
and if he hadn't noticed, he wouldn't have been able to use password recovery because the app doesn't have his correct email. Email confirmation only provides limited protection against bots and no protection against determined spammers, they have many working email aliases they can use to register.
You generally want to prevent new users from posting any information to your website before they have been verified by email, text message, or other mechanism.In the sections below, we will enable email verification and modify the code to prevent newly registered users from logging in until their email is verified.
Merge SendGrid
The instructions in this section are out of date. SeeConfigure the SendGrid email service providerfor updated instructions.
Although this tutorial only shows how to add an email notificationSendGrid, you can send email using SMTP and other mechanisms (seeadditional funds).
In the package manager console, enter the following command:
Installing the SendGrid package
To live inAzure SendGrid login pageand register for a free SendGrid account. Configure SendGrid by adding code similar to the following to theApp_Start/IdentityConfig.cs:
public class EmailService : IIdentityMessageService{ public async Task SendAsync(IdentityMessage message) { await configSendGridasync(message); } // Use NuGet to install SendGrid (Basic C# client lib) private async Task configSendGridasync(IdentityMessage message) { var myMessage = new SendGridMessage(); myMessage.AddTo(message.Destination); myMessage.From = new System.Net.Mail.MailAddress( "Joe@contoso.com", "Joe S."); myMessage.Subject = message.Subject; myMessage.Text = message.Body; myMessage.Html = message.Body; var credentials = new NetworkCredential( ConfigurationManager.AppSettings["mailAccount"], ConfigurationManager.AppSettings["mailPassword"]); // Create a webcast to send the email. var transportWeb = new Web(credentials); // Send email. if (transportWeb != null) { await transportWeb.DeliverAsync(myMessage); } else { Trace.TraceError("Failed to create webcast."); await Task.FromResult(0); } }}
You will need to add the following includes:
using SendGrid; using System.Net; using System.Configuration; using System.Diagnostics;
To keep this sample simple, we'll store the app's settings inweb.configfile:
Warning
Security - Never store sensitive data in your source code. Account and credentials are stored in AppSetting. On Azure, you can safely store these values atConfiguretab in the Azure portal. SeeBest practices for implementing passwords and other sensitive data on ASP.NET and Azure.
Enable email verification in Account Controller
//// POST: /Account/Register[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async TaskRegister(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) { await SignInManager.SignInAsync(user, isPersistent:false, RememberBrowser:false); string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protokol: Request.Url.Scheme); await UserManager.SendEmailAsync(user.Id, "Potvrdite svoj račun", "Molimo potvrdite svoj račun klikom nahere"); return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something went wrong, show the form again return View(model);}
Check it outViews\Account\ConfirmEmail.cshtmlfile has the correct razor syntax. (The @ sign may be missing in the first line.)
@{ ViewBag.Title = "Confirm Email";}@ViewBag.Title.
Thank you for confirming your email. Please @Html.ActionLink("Click here to login", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })
Launch the application and click on the Registration link. After submitting the registration form, you are logged in.
Check your email account and click on the link to verify your email.
Require email confirmation before signing up
Currently, when a user fills out the registration form, they are logged in. You generally want to confirm his email before signing up. In the section below, we will modify the code so that new users should have a verified email before signing up (authenticated). Please updateHttpPost Registration
method with the following notable changes:
//// POST: /Account/Register[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async TaskRegister(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) { // Comment out the following line to prevent login until the user is authenticated. // wait SignInManager.SignInAsync(user, isPersistent:false, RememberBrowser:false); string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); await UserManager.SendEmailAsync(user.Id, "Verify your account", "Please verify your account by clickinghere"); // Uncomment for local debugging // TempData["ViewBagLink"] = callbackUrl; ViewBag.Message = "Check your email and verify your account, you must be verified " + "before you can login. "; return View("Information"); //return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something went wrong, show the form again return View(model) ;}
By commentingSignInAsync
way, the user will not be logged in through registration. TheTempData["ViewBagLink"] = callbackUrl;
line can be used fordebug the applicationand trial registration without sending e-mail.ViewBag.Message
used to display confirmation instructions. Thesample downloadcontains code to test email confirmation without setting up an email, and can also be used to debug the application.
To createViews\Shared\Information.cshtml
file and add the following razor tags:
@{ ViewBag.Title = "Information";}@ViewBag.Title.
@ViewBag.Message
AddAuthorization attributeaccording toContact
mode of operation of the Home controller. You can click onContactlink to verify that anonymous users do not have access and authenticated users do.
[Authorize]public ActionResult Contact(){ ViewBag.Message = "Your contact page."; return View();}
You also need to updateHttpPost Login
mode of action:
//// POST: /Account/Login[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async TaskLogin(LoginViewModel model, string returnUrl){ if (!ModelState.IsValid) { return View(model); } // Requires the user to have a verified email before they can login. var user = await UserManager.FindByNameAsync(model.Email); if (user != null) { if (!await UserManager.IsEmailConfirmedAsync(user.Id)) { ViewBag.errorMessage = "You must have a confirmed email to log in."; return View("Error"); } } // This does not count failed logins against account lockout // To allow failed passwords to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return View(model); }}
Please updateViews\Shared\Error.cshtmldisplay to display the error message:
@model System.Web.Mvc.HandleErrorInfo@{ ViewBag.Title = "Greška";}Error.
@{ if (String.IsNullOrEmpty(ViewBag.errorMessage)) {An error occurred while processing your request.
} else {@ViewBag.errorMessage
}}
Delete all accounts inAspNetUserstable containing the email alias you want to test with. Launch the app and confirm that you cannot sign in until you verify your email address. After confirming your email address, clickContactconnection.
Password recovery/reset
Remove comment characters fromHttpPost ForgotPassword
method of operation in the account controller:
//// POST: /Account/ForgotPassword[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async TaskForgotPassword(ForgotPasswordViewModel model){ if (ModelState.IsValid) { var user = await UserManager.FindByNameAsync(model.Email) ; if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) { // Do not detect that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); await UserManager.SendEmailAsync(user.Id, "Reset password", "Reset password by clickinghere"); return RedirectToAction("ForgotPasswordConfirmation", "Account"); } // If we got this far, something went wrong, show the form again return View(model);}
Remove comment characters fromYou forgot your password
ActionLinkuViews\Account\Login.cshtmlrazor preview file:
@using MvcPWy.Models@model LoginViewModel@{ ViewBag.Title = "Prijava";}@ViewBag.Title.
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", uloga = "form" })) { @Html.AntiForgeryToken()Use a local account to sign in.
@Html.ValidationSummary(true, "", new { @class = "text -danger" })@Html.LabelFor(m => m.E-pošta, novo { @class = "col-md-2 control-label" })@Html.TextBoxFor(m => m.E-pošta, novo { @class = "form-control" }) @Html.ValidationMessageFor(m => m.E-pošta, "", novo { @class = "text-danger" }) @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control- label" })@Html.PasswordFor(m => m.Password, nova { @class = "form-control" }) @Html.ValidationMessageFor(m => m. Lozinka, "", novo { @class = "text-danger" }) @Html.CheckBoxFor(m => m.RememberMe) @Html.LabelFor(m => m.RememberMe) @Html.ActionLink("Register as a new user", "Register")
@* Enable this after enabling account verification for password reset functionality *@@Html.ActionLink("Forgot your password?", "Forgot your password")
} (Video) Create Login Page in Asp.net (MVC 5 & SQL Server)@section Scripts { @Scripts.Render("~/bundles/jqueryval")}
The login page will now display a password reset link.
Resend the confirmation link via email
After a user creates a new local account, they are emailed a confirmation link that they must use before they can log in. If the user accidentally deletes the confirmation email or the email never arrives, they will need to resend the confirmation link. The following code changes show how to enable this.
Add the following helper method to the bottomControllers\AccountController.csfile:
private async TaskSendEmailConfirmationTokenAsync(string userID, string subject){ string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = userID, code = code }, protokol: Request.Url.Scheme); await UserManager.SendEmailAsync(userID, subject, "Molimo potvrdite svoj račun klikom nahere"); return callbackUrl;}
Update the Register method to use the new helper:
//// POST: /Account/Register[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async TaskRegister(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) { // Comment out the following line to prevent login until the user is authenticated. // wait SignInManager.SignInAsync(user, isPersistent:false, RememberBrowser:false); string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account"); ViewBag.Message = "Check your email and verify your account, you must be verified " + "before you can log in."; return View("Information"); //return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something went wrong, show the form again return View(model);}
Update login method to resend password if user account is not verified:
//// POST: /Account/Login[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async TaskLogin(LoginViewModel model, string returnUrl){ if (!ModelState.IsValid) { return View(model); } // Requires the user to have a verified email before they can login. // var user = await UserManager.FindByNameAsync(model.Email); var user = UserManager.Find(model.Email, model.Password); if (user != null) { if (!await UserManager.IsEmailConfirmedAsync(user.Id)) { string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account-resend"); // Uncomment for local debugging // ViewBag.Link = callbackUrl; ViewBag.errorMessage = "You must have a verified email to sign in. " + "A verification token has been resent to your email account."; return View("Error"); } } // This does not count failed logins against account lockout // To allow failed passwords to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return View(model); }}
Combine social and local login accounts
You can combine local and social accounts by clicking the link in your email. In the next sequenceRickAndMSFT@gmail.comit is first created as a local login, but you can create the account as a social login first and then add a local login.
Click hereGovernconnection. Pay attention toExternal applications: 0associated with this account.
Click the link to another service to sign in and accept the application's requirements. The two accounts are merged, you will be able to log in with either account. You may want your users to add local accounts in case their social login authentication service is down or more likely they have lost access to their social account.
In the next image, Tom is social logged in (as you can see from theExternal applications: 1displayed on the page).
By clicking onChoose a passwordallows you to add a local login associated with the same account.
More detailed email confirmation
My tutorialAccount verification and password recovery with ASP.NET identitygoes into this topic in more detail.
Debug the application
If you do not receive an email with a link:
- Check your junk or spam folder.
- Log in to your SendGrid account and click onEmail activity link.
To test the confirmation link without email, please downloadcompleted sample. A verification link and verification codes will be displayed on the page.
Additional funds
- Links to recommended resources for ASP.NET Identity
- Account verification and password recovery with ASP.NET identityIt goes into detail about password recovery and account verification.
- MVC 5 application with Facebook, Twitter, LinkedIn and Google OAuth2 loginThis tutorial shows you how to write an ASP.NET MVC 5 application with Facebook and Google OAuth 2 authorization. It also shows how to add additional data to the identity database.
- Deploy a secure ASP.NET MVC application with membership, OAuth, and a SQL database on Azure. This guide adds Azure deployment, how to secure your application with roles, how to use the membership API to add users and roles, and additional security features.
- Creating a Google application for OAuth 2 and connecting the application to the project
- Creating an application on Facebook and connecting the application to the project
- Setting up SSL in the project
FAQs
How to reset password in MVC 5? ›
- public ActionResult ResetPassword(string code, string email)
- {
- ResetPasswordModel model = new ResetPasswordModel();
- model. ReturnToken = code;
- return View(model);
- }
- [HttpPost]
- public ActionResult ResetPassword(ResetPasswordModel model)
- Step 1: Create Project. Go to FILE, New, then click on Project.
- Step 2: Add Entity Data Model. Go to Solution Explorer, Right Click on Project, Add, then select ADO.NET Entity Data Model.
- Step 3: Add a Controller. ...
- Step 4: Create Views.
- Step 5: Set as StartUp Page. ...
- Step 6: Run the Application.
First, create a role and then assign it to the user. Then, send an email confirmation link on the registration time. For send an email confirmation link, first get the HTML template and add a dynamic value, such as a username confirmation link. The ASP.NET identity generates a call-back URL, which sends in the email.
How to reset password in ASP.NET c#? ›- If you're signed in, select Logout.
- Select the Log in link and select the Forgot your password? link.
- Enter the email you used to register the account.
- An email with a link to reset your password is sent. Check your email and click the link to reset your password.
- The URL of the password reset page is determined by the route of the corresponding MVC action.
- The validity of password reset requests depends on your application's ASP.NET Identity configuration (1 day by default).
- Select Forgot password? If the Enter password window is still open select Forgot password? ...
- Verify your identity. For your protection, Microsoft must verify your identity before you can proceed with resetting your password. ...
- Get a verification code. ...
- Enter code and reset password.
- Create New Asp.Net MVC Application.
- Adding Authentication Filter.
- Below is Code Snippet of UserAuthenticationFilter.
- Adding LoginModel.
- Adding UserLogin Controller.
- See below Snapshot of UserLogin Controller.
- Applying UserAuthentication Filter on Home Controller.
- Start Visual Studio and select Create a new project.
- In the Create a new project dialog, select ASP.NET Core Web Application > Next.
- In the Configure your new project dialog, enter MvcMovie for Project name. ...
- Select Create.
- In the Create a new ASP.NET Core web application dialog, select:
- Scaffold Your ASP.NET Project.
- Configure User Registration.
- Configure Basic User Authentication.
- Add . ...
- Configure Your ASP.NET App for Login.
- Add Login to Your ASP.NET App.
- Register Users.
- Log In Using ASP.NET.
- Start a new MVC project.
- Give it some name.
- Select ASP.NET template.
- Open your Home Controller (or any controller)
- In Controller, create an ActionResult method SendEmail (you can give it any name). ...
- Add an empty View for this action method and add the following code.
How to send email automatically using ASP.NET c#? ›
var mailMessage = new MailMessage { From = new MailAddress("email"), Subject = "subject", Body = "<h1>Hello</h1>", IsBodyHtml = true, }; mailMessage. To. Add("recipient"); smtpClient. Send(mailMessage);
How to implement form authentication in ASP.NET MVC? ›- In the web. config file, set the authentication mode to Forms.
- FormsAuthentication. SetAuthCookie is required to use for login.
- Again FormAuthentication. SignOut is required to use for logout.
- Example Of First Enter Password = "rraannaammeett"
- EncodePasswordToBase64 function converts your string and gives output. ans= "cnJhYW5uYWFtbWVldHQ="
- DecodeFrom64 function convert your strring and give output. ans="rraannaammeett"
The Login control contains text boxes for the user name and password and a check box that allows users to indicate whether they want the server to store their identity using ASP.NET membership and automatically be authenticated the next time they visit the site.
How to encrypt password in Web API C#? ›- First we create a Web API application as in the following: Start Visual Studio 2012. ...
- Create a Model class as in the following: In the "Solution Explorer". ...
- In the "HomeController" write the code to encrypt and decrypt the text. ...
- Now use the "index. ...
- Execute the application.
TP-LINK Archer C5 Routers Support
Forgot Login Password? Try the hard reset function. In order to do this, press and hold the small black button usually situated at the back your router case for approximately 10 seconds. Doing so will reset your router to the factory settings.
- Log in to the vCenter Server with a domain administrator account. ...
- Open an elevated command prompt.
- Navigate to the vmdird directory by running the command: ...
- Run c:\Program Files\VMware\Infrastructure\VMware\CIS\vmdird\vdcadmintool.exe. ...
- Press 3 to enter the Reset account password option.
To change the administrator password on a virtual machine (VM) with a Windows OS, go to Virtual Machines → select VM → menu → Change Password and enter the new password. In some cases, such as OS failures, the password may not change.
How do I reset my VMware identity manager password? ›Log in to the connector admin pages at https:// connectorFQDN :8443/cfg/login as the admin user. Click Change Password. Enter the old and new passwords. Important: The admin user password must be at least 6 characters in length.