Which Of The Following Account Have A Register Associated With Them
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Account confirmation and password recovery with ASP.NET Identity (C#)
Before doing this tutorial y'all should first complete Create a secure ASP.NET MVC 5 web app with log in, email confirmation and countersign reset. This tutorial contains more details and will show you how to ready upwards email for local account confirmation and permit users to reset their forgotten password in ASP.Internet Identity.
A local user account requires the user to create a password for the account, and that countersign is stored (securely) in the web app. ASP.Cyberspace Identity also supports social accounts, which don't require the user to create a password for the app. Social accounts utilise a third party (such as Google, Twitter, Facebook, or Microsoft) to cosign users. This topic covers the following:
- Create an ASP.Net MVC app and explore ASP.NET Identity features.
- Build the Identity sample
- Set upward e-mail confirmation
New users register their email alias, which creates a local account.
Selecting the Annals push sends a confirmation electronic mail containing a validation token to their e-mail address.
The user is sent an email with a confirmation token for their account.
Selecting the link confirms the account.
Password recovery/reset
Local users who forget their password can have a security token sent to their email account, enabling them to reset their password.
The user will soon become an e-mail with a link allowing them to reset their password.
Selecting the link will take them to the Reset page.
Selecting the Reset button will confirm the password has been reset.
Create an ASP.Internet web app
Kickoff by installing and running Visual Studio 2017.
-
Create a new ASP.Internet Spider web project and select the MVC template. Spider web Forms also support ASP.NET Identity, and so y'all could follow like steps in a web forms app.
-
Change the authentication to Individual User Accounts.
-
Run the app, select the Register link and annals a user. At this point, the simply validation on the electronic mail is with the [EmailAddress] attribute.
-
In Server Explorer, navigate to Information Connections\DefaultConnection\Tables\AspNetUsers, right-click and select Open table definition.
The post-obit prototype shows the
AspNetUsers
schema: -
Correct-click on the AspNetUsers table and select Show Tabular array Data.
At this bespeak the email has not been confirmed.
The default data store for ASP.NET Identity is Entity Framework, simply you can configure it to use other data stores and to add additional fields. Encounter Additional Resources section at the end of this tutorial.
The OWIN startup grade ( Startup.cs ) is called when the app starts and invokes the ConfigureAuth
method in App_Start\Startup.Auth.cs, which configures the OWIN pipeline and initializes ASP.NET Identity. Examine the ConfigureAuth
method. Each CreatePerOwinContext
phone call registers a callback (saved in the OwinContext
) that will be called in one case per request to create an case of the specified blazon. Yous can set a intermission point in the constructor and Create
method of each type (ApplicationDbContext, ApplicationUserManager
) and verify they are called on each request. A instance of ApplicationDbContext
and ApplicationUserManager
is stored in the OWIN context, which can be accessed throughout the application. ASP.NET Identity hooks into the OWIN pipeline through cookie middleware. For more information, encounter Per asking lifetime management for UserManager class in ASP.NET Identity.
When you alter your security profile, a new security stamp is generated and stored in the SecurityStamp
field of the AspNetUsers tabular array. Note, the SecurityStamp
field is different from the security cookie. The security cookie is non stored in the AspNetUsers
table (or anywhere else in the Identity DB). The security cookie token is cocky-signed using DPAPI and is created with the UserId, SecurityStamp
and expiration time information.
The cookie middleware checks the cookie on each request. The SecurityStampValidator
method in the Startup
class hits the DB and checks security stamp periodically, as specified with the validateInterval
. This but happens every thirty minutes (in our sample) unless you change your security contour. The thirty infinitesimal interval was called to minimize trips to the database. See my two-factor authentication tutorial for more details.
Per the comments in the code, the UseCookieAuthentication
method supports cookie authentication. The SecurityStamp
field and associated code provides an extra layer of security to your app, when you change your password, you lot will be logged out of the browser you logged in with. The SecurityStampValidator.OnValidateIdentity
method enables the app to validate the security token when the user logs in, which is used when yous change a password or utilize the external login. This is needed to ensure that any tokens (cookies) generated with the old countersign are invalidated. In the sample project, if you change the users countersign and then a new token is generated for the user, any previous tokens are invalidated and the SecurityStamp
field is updated.
The Identity system let you to configure your app so when the users security contour changes (for example, when the user changes their countersign or changes associated login (such as from Facebook, Google, Microsoft account, etc.), the user is logged out of all browser instances. For example, the image beneath shows the Single signout sample app, which allows the user to sign out of all browser instances (in this example, IE, Firefox and Chrome) by selecting one button. Alternatively, the sample allows you to simply log out of a specific browser instance.
The Single signout sample app shows how ASP.NET Identity allows you to regenerate the security token. This is needed to ensure that any tokens (cookies) generated with the former password are invalidated. This feature provides an extra layer of security to your application; when you lot modify your password, you volition be logged out where yous accept logged into this awarding.
The App_Start\IdentityConfig.cs file contains the ApplicationUserManager
, EmailService
and SmsService
classes. The EmailService
and SmsService
classes each implement the IIdentityMessageService
interface, then you have common methods in each class to configure email and SMS. Although this tutorial merely shows how to add email notification through SendGrid, y'all tin can send email using SMTP and other mechanisms.
The Startup
class too contains boiler plate to add together social logins (Facebook, Twitter, etc.), see my tutorial MVC 5 App with Facebook, Twitter, LinkedIn and Google OAuth2 Sign-on for more than info.
Examine the ApplicationUserManager
form, which contains the users identity data and configures the post-obit features:
- Password forcefulness requirements.
- User lock out (attempts and time).
- Two-factor authentication (2FA). I'll cover 2FA and SMS in another tutorial.
- Hooking up the email and SMS services. (I'll cover SMS in another tutorial).
The ApplicationUserManager
grade derives from the generic UserManager<ApplicationUser>
class. ApplicationUser
derives from IdentityUser. IdentityUser
derives from the generic IdentityUser
class:
// Default EntityFramework IUser implementation public class IdentityUser<TKey, TLogin, TRole, TClaim> : IUser<TKey> where TLogin : IdentityUserLogin<TKey> where TRole : IdentityUserRole<TKey> where TClaim : IdentityUserClaim<TKey> { public IdentityUser() { Claims = new List<TClaim>(); Roles = new List<TRole>(); Logins = new List<TLogin>(); } /// User ID (Primary Fundamental) public virtual TKey Id { become; set; } public virtual string Email { get; set; } public virtual bool EmailConfirmed { go; set up; } public virtual string PasswordHash { go; set; } /// A random value that should alter whenever a users credentials take inverse (password changed, login removed) public virtual string SecurityStamp { get; set; } public virtual cord PhoneNumber { go; set; } public virtual bool PhoneNumberConfirmed { get; set; } public virtual bool TwoFactorEnabled { get; set; } /// DateTime in UTC when lockout ends, any time in the by is considered not locked out. public virtual DateTime? LockoutEndDateUtc { get; fix; } public virtual bool LockoutEnabled { get; set; } /// Used to record failures for the purposes of lockout public virtual int AccessFailedCount { get; gear up; } /// Navigation property for user roles public virtual ICollection<TRole> Roles { get; private ready; } /// Navigation holding for user claims public virtual ICollection<TClaim> Claims { go; private prepare; } /// Navigation property for user logins public virtual ICollection<TLogin> Logins { get; private set; } public virtual string UserName { get; set; } }
The properties higher up coincide with the properties in the AspNetUsers
table, shown higher up.
Generic arguments on IUser
enable you lot to derive a form using dissimilar types for the master key. Run into the ChangePK sample which shows how to alter the primary key from string to int or GUID.
ApplicationUser
ApplicationUser
(public form ApplicationUserManager : UserManager<ApplicationUser>
) is divers in Models\IdentityModels.cs every bit:
public form ApplicationUser : IdentityUser { public async Chore<ClaimsIdentity> GenerateUserIdentityAsync( UserManager<ApplicationUser> manager) { // Note the authenticationType must match the ane defined in // CookieAuthenticationOptions.AuthenticationType var userIdentity = look managing director.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add together custom user claims here return userIdentity; } }
The highlighted code higher up generates a ClaimsIdentity. ASP.NET Identity and OWIN Cookie Hallmark are claims-based, therefore the framework requires the app to generate a ClaimsIdentity
for the user. ClaimsIdentity
has information well-nigh all the claims for the user, such as the user'southward name, age and what roles the user belongs to. You tin can also add more claims for the user at this stage.
The OWIN AuthenticationManager.SignIn
method passes in the ClaimsIdentity
and signs in the user:
private async Job SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); AuthenticationManager.SignIn(new AuthenticationProperties(){ IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager)); }
MVC five App with Facebook, Twitter, LinkedIn and Google OAuth2 Sign-on shows how yous can add additional properties to the ApplicationUser
class.
Email confirmation
Information technology'south a adept idea to confirm the electronic mail a new user register with to verify they are non impersonating someone else (that is, they oasis't registered with someone else's e-mail). Suppose yous had a discussion forum, you would want to forestall "bob@instance.com"
from registering every bit "joe@contoso.com"
. Without e-mail confirmation, "joe@contoso.com"
could become unwanted e-mail from your app. Suppose Bob accidentally registered as "bib@example.com"
and hadn't noticed it, he wouldn't be able to use countersign recover because the app doesn't have his right email. E-mail confirmation provides only express protection from bots and doesn't provide protection from determined spammers, they take many working email aliases they tin can use to register.In the sample beneath, the user won't be able to change their password until their account has been confirmed (by them selecting a confirmation link received on the electronic mail account they registered with.) You tin utilise this work flow to other scenarios, for instance sending a link to confirm and reset the password on new accounts created past the ambassador, sending the user an email when they have changed their profile and and so on. Yous mostly want to prevent new users from posting any information to your web site before they have been confirmed by email, a SMS text bulletin or another mechanism.
Build a more consummate sample
In this section, you'll employ NuGet to download a more complete sample we volition piece of work with.
-
Create a new empty ASP.NET Web project.
-
In the Packet Manager Console, enter the post-obit commands:
Install-Parcel SendGrid Install-Packet -Prerelease Microsoft.AspNet.Identity.Samples
In this tutorial, we'll use SendGrid to send email. The
Identity.Samples
package installs the lawmaking nosotros volition exist working with. -
Set the project to utilize SSL.
-
Test local account creation by running the app, selecting the Register link, and posting the registration form.
-
Select the demo email link, which simulates e-mail confirmation.
-
Remove the demo email link confirmation code from the sample (The
ViewBag.Link
code in the business relationship controller. See theDisplayEmail
andForgotPasswordConfirmation
activity methods and razor views ).
Warning
If you lot change any of the security settings in this sample, productions apps will demand to undergo a security audit that explicitly calls the changes fabricated.
Examine the lawmaking in App_Start\IdentityConfig.cs
The sample shows how to create an account and add together it to the Admin role. You should supersede the email in the sample with the email you lot will be using for the admin business relationship. The easiest way right now to create an ambassador account is programmatically in the Seed
method. We hope to have a tool in the futurity that volition permit yous to create and administrate users and roles. The sample lawmaking does let you create and manage users and roles, just you must kickoff have an administrators account to run the roles and user admin pages. In this sample, the admin account is created when the DB is seeded.
Change the password and change the name to an account where yous can receive email notifications.
Warning
Security - Never shop sensitive data in your source lawmaking.
As mentioned previously, the app.CreatePerOwinContext
call in the startup form adds callbacks to the Create
method of the app DB content, user manager and role manger classes. The OWIN pipeline calls the Create
method on these classes for each request and stores the context for each form. The account controller exposes the user manager from the HTTP context (which contains the OWIN context):
public ApplicationUserManager UserManager { become { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } }
When a user registers a local business relationship, the HTTP Post Register
method is called:
[HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Chore<ActionResult> Annals(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, E-mail = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var code = wait 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, "Confirm your account", "Please confirm your account past clicking this link: <a href=\"" + callbackUrl + "\">link</a>"); // ViewBag.Link = callbackUrl; // Used simply for initial demo. return View("DisplayEmail"); } AddErrors(result); } // If nosotros got this far, something failed, redisplay course return View(model); }
The code to a higher place uses the model data to create a new user account using the email and password entered. If the email alias is in the data store, account creation fails and the form is displayed again. The GenerateEmailConfirmationTokenAsync
method creates a secure confirmation token and stores it in the ASP.Net Identity data store. The Url.Action method creates a link containing the UserId
and confirmation token. This link is then emailed to the user, the user can select on the link in their email app to ostend their account.
Gear up e-mail confirmation
Go to the SendGrid sign up folio and register for free account. Add code similar to the post-obit to configure SendGrid:
public course EmailService : IIdentityMessageService { public Chore SendAsync(IdentityMessage bulletin) { render configSendGridasync(message); } private Job configSendGridasync(IdentityMessage message) { var myMessage = new SendGridMessage(); myMessage.AddTo(message.Destination); myMessage.From = new Organization.Cyberspace.Mail.MailAddress( "Joe@contoso.com", "Joe Due south."); myMessage.Subject = message.Subject field; myMessage.Text = message.Body; myMessage.Html = message.Trunk; var credentials = new NetworkCredential( ConfigurationManager.AppSettings["mailAccount"], ConfigurationManager.AppSettings["mailPassword"] ); // Create a Web transport for sending email. var transportWeb = new Web(credentials); // Ship the electronic mail. if (transportWeb != null) { return transportWeb.DeliverAsync(myMessage); } else { return Chore.FromResult(0); } } }
Note
E-mail clients oft take only text messages (no HTML). You should provide the bulletin in text and HTML. In the SendGrid sample to a higher place, this is done with the myMessage.Text
and myMessage.Html
lawmaking shown in a higher place.
The following code shows how to send e-mail using the MailMessage class where bulletin.Torso
returns only the link.
void sendMail(Message bulletin) { #region formatter string text = string.Format("Please click on this link to {0}: {ane}", bulletin.Discipline, message.Trunk); string html = "Please confirm your account by clicking this link: <a href=\"" + message.Body + "\">link</a><br/>"; html += HttpUtility.HtmlEncode(@"Or click on the copy the post-obit link on the browser:" + bulletin.Torso);
0 Response to "Which Of The Following Account Have A Register Associated With Them"
Post a Comment