This article uses ASP. NET Identity 2.0 in MVC to experience functions related to user Identity security:
→ Install-package Microsoft. AspNet. Identity. Samples-Version 2.0.0-beta2-Pre
After installation, multiple files are added in App_Start, Controllers, Models, Views, and so on. There are 6 classes and an enumeration in App_Start/IdentityConfig. cs:
● ApplicationUserManager: inherits from the generic base class UserManager <ApplicationUser>. ApplicationUser is used to process the user's identity.
● ApplicationRoleManager
● EmailService
● SmsService
● ApplicationDbInitializer
● SignInHelper
● SignInStatus Enumeration
□Two-Factor Authentication mechanism
In ASP. NET Identity 2.0 uses the "Two-Factor Authentication mechanism" to ensure the security of the user's password. When the user's password may be insecure, the system sends a security code to the user by text message or email.
The Create method in ApplicationUserManager contains the logic for verifying the user name and password and sending the security code:
Both PhoneNumberTokenProvider and EmailTokenProvider inherit from EmailTokenProvider. This base class is used to send text messages or emails to users. The premise of sending is to register EmailService and SmsService, as follows:
□Account Lockout
When the user enters the wrong password more than the specified number of times, the account will be locked.
The Create method in ApplicationUserManager also contains the logic for locking accounts:
→ Write the logic of right-click sending in EmailService:
Public class EmailService: IIdentityMessageService {public Task SendAsync (IdentityMessage message) {// Plug in your email service here to send an email. // configure var mailMessage = new System. net. mail. mailMessage ("qdjjx9441@sina.com", message. destination, message. subject, message. body) // send SmtpClient client = new SmtpClient (); client. sendAsync (mailMessage, null); return Task. fromResult (0 );}}
→ Configure the email receiving folder under the <configuration> node in Web. config
<System.net>
<MailSettings>
<Smtp deliveryMethod = "SpecifiedPickupDirectory">
<SpecifiedPickupDirectory pickupDirectoryLocation = "F: \ mailDrop"/>
</Smtp>
</MailSettings>
</System.net>
→ Configure the connection string for the <connectionStrings> node in Web. config to save user information to the database.
<add name="DefaultConnection" connectionString=".;Initial Catalog=MVC_Identity-1-14;user id=sa;password=woshiniba;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
→ The Register Method for receiving [HttpPost] In AccontController contains the logic for sending confirmation emails after the user registers
[HttpPost] [AllowAnonymous] [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) { var 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, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>"); ViewBag.Link = callbackUrl; return View("DisplayEmail"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); }
→ Run the project test registration, confirmation email, and login
Click the Register link in the upper-right corner:
Enter the registration information and click "register:
Note: You must create the mailDrop folder configured in Web. config. Otherwise, an error is returned!
Find the mailDrop folder and use Foxmail to open the file with the suffix eml. You can see:
Click link:
Click "Click here to Log in" and Log on:
→ Locked the account for running the project test
In App_Start/IdentityConfig. cs, the related part of the ApplicationUserManager class is:
Manager. UserLockoutEnabledByDefault = true;
Manager. DefaultAccountLockoutTimeSpan = TimeSpan. FromMinutes (1 );
Manager. MaxFailedAccessAttemptsBeforeLockout = 2;
In App_Start/IdentityConfig. cs, modify PasswordSignIn of the SignInHelper class as follows:
Public async Task <SignInStatus> PasswordSignIn (string userName, string password, bool isPersistent, bool shouldLockout) {var user = await UserManager. findByNameAsync (userName); // Add await UserManager to lock the test account. isLockedOutAsync (user. id); // if the user is locked, return true await UserManager here. accessFailedAsync (user. id); // record the number of Logon failures. If the number of Logon failures is greater than or equal to the set number of Logon failures, the user account is locked for await UserManager within the set lock time. setLockoutEnabledAsync (user. id, true); // check whether the user account is locked. if (user = null) {return SignInStatus. failure;} if (await UserManager. isLockedOutAsync (user. id) {return SignInStatus. lockedOut;} if (await UserManager. checkPasswordAsync (user, password) {return await SignInOrTwoFactor (user, isPersistent);} if (shouldLockout) {// If lockout is requested, increment access failed count which might lock out the user await UserManager. accessFailedAsync (user. id); if (await UserManager. isLockedOutAsync (user. id) {return SignInStatus. lockedOut;} return SignInStatus. failure ;}
Log on again and try to enter the wrong password twice. The system prompts that the account is locked:
Of course, there are some other functions, such as password reset.
References:
Developing Secure ASP. net mvc Applications using ASP. NET Identity 2.0
Github Project address