This article experiences the use of ASP. NET identity 2.0 to experience features related to user identity security:
→install-package microsoft.aspnet.identity.samples-version 2.0.0-beta2-pre
After installation, in App_start,controllers, Models, views and other places have added a number of files. 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 handle the user's identity.
Applicationrolemanager
Emailservice
SMSService
Applicationdbinitializer
Signinhelper
Signinstatus Enumeration
-two-factor authentication mechanism
In the ASP. NET Identity 2.0, the "Two-factor authentication mechanism" is used to ensure the security of the user's password, and when the user's password may be unsafe, the system will send a security code to the user in the form of text message or mail.
The Create method in Applicationusermanager contains the logic to verify the user name and password and to send the security code:
Both Phonenumbertokenprovider and emailtokenprovider inherit from Emailtokenprovider, the base class responsible for sending SMS or email to users. The prerequisites for sending are to register Emailservice and SMSService as follows:
-account Lockout lock Account
When the user loses the wrong password more than the specified number of times, the account will be locked.
The Create method in Applicationusermanager also contains the logic to lock the account:
→ write logic to send right-click in Emailservice:
Public classEmailservice:iidentitymessageservice { PublicTask SendAsync (identitymessage message) {//Plug in your e-mail service here-to-send an email. //Configuration varMailMessage =NewSystem.Net.Mail.MailMessage ("[email protected]", message. Destination, message. Subject, message. Body)//SendSmtpClient client =NewSmtpClient (); Client. SendAsync (MailMessage,NULL); returnTask.fromresult (0); } }
→ Configure the folder to receive messages 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 in the <connectionStrings> node in Web. config to save the user information to the database
<add name="defaultconnection " connectionstring=".; I Nitial catalog=mvc_identity-1-14;user id=sa;password=woshiniba;integrated security=sspi"
Providername="System.Data.SqlClient" />
The Register method receiving [HttpPost] in →accontcontroller contains the logic to send a confirmation message after the user has registered
[ HttpPost] [allowanonymous] [Validateantiforgerytoken] Public AsyncTask<actionresult>Register (Registerviewmodel model) {if(modelstate.isvalid) {varuser =NewApplicationUser {UserName = model. email, email =model. Email}; varresult =awaitusermanager.createasync (user, model. Password); if(result.) Succeeded) {varCode =awaitusermanager.generateemailconfirmationtokenasync (user. ID); varCallbackurl = Url.action ("Confirmemail"," Account",New{userId = user. Id, code =code}, Protocol:Request.Url.Scheme); awaitUsermanager.sendemailasync (user. Id"Confirm your account","confirm your account by clicking this link: <a href=\ ""+ Callbackurl +"\ ">link</a>"); Viewbag.link=Callbackurl; returnView ("Displayemail"); } adderrors (Result); } //If We got this far, something failed, redisplay form returnView (model); }
→ Run Project test registration, confirmation email, login
Click on the register link at the top right:
To fill in the registration information, click Register:
Note: The Maildrop folder that is configured in Web. config needs to be created, otherwise error!
Locate the Maildrop folder and use Foxmail to open the file with the suffix eml to see:
Click the link address:
Click "Click here to log in" and log in:
→ Run Project test account lockout
To modify App_start/identityconfig.cs, the relevant parts of the Applicationusermanager class are:
Manager. Userlockoutenabledbydefault = true;
Manager. Defaultaccountlockouttimespan = timespan.fromminutes (1);
Manager. Maxfailedaccessattemptsbeforelockout = 2;
In App_start/identityconfig.cs, the passwordsignin of the Signinhelper class is modified as follows:
Public AsyncTask<signinstatus> Passwordsignin (stringUserName,stringPasswordBOOLIspersistent,BOOLshouldlockout) { varuser =awaitUsermanager.findbynameasync (userName); //add to test account lockout awaitUsermanager.islockedoutasync (user. ID);//If the user is locked, this returns true awaitUsermanager.accessfailedasync (user. ID);//Log the number of login failures, and if the number of failed logins is greater than or equal to the set number of times, the user account is locked during the set lock time awaitUsermanager.setlockoutenabledasync (user. Gdbtrue);//confirm that the user account is locked and is enabled if(User = =NULL) { returnsigninstatus.failure; } if(awaitusermanager.islockedoutasync (user. Id)) {returnsigninstatus.lockedout; } if(awaitusermanager.checkpasswordasync (user, password)) { return awaitsigninortwofactor (user, ispersistent); } if(shouldlockout) {//If lockout is requested, increment access failed count which might lock out the user awaitusermanager.accessfailedasync (user. ID); if(awaitusermanager.islockedoutasync (user. Id)) {returnsigninstatus.lockedout; } } returnsigninstatus.failure; }
Log in again, try to enter 2 error password, there is a prompt account locked interface:
There are, of course, some other features, such as password reset.
Resources:
Developing Secure ASP. Applications using ASP. NET Identity 2.0
GitHub Project Address