Elasticsearch Full Text Search analysis of the basic operation of the Index series (IV.)

Source: Internet
Author: User

Today, reading is sometimes a matter of "trouble". It takes time, energy, and a mind to pay. --only to "elasticsearch full-Text Search Analysis series" to mourn the passing of ...

After using VS2015 to create an MVC project run, I found that Microsoft is very intimate to generate a set of user authorization verification system, the interface is very beautiful, but BA la code to see, embarrassed ... The new membership framework is so strong that even database tables are generated for you (EF credit), the problem is that you heap a bunch of code, though looking very hanging (also

Really very hanging), but look at the big head, have to study, research process record, hope can help those who see this heap of code after also scalp numbness of small partners!!!

First step: Delete this heap of code

Microsoft is tossing a bunch of code, to be honest about Microsoft's various ViewModel verification does not have a cold, so I want to delete it, re-come! Like to use the children's shoes, can keep

Note: Kiss, do not delete all, please keep the Identitymodels class, modify the namespace, and move it into the App_start directory

  

Step two: Pull out the SQL statement that automatically generates the data table (because the MySQL database is used later, and the engine is not InnoDB)

CREATE TABLE Aspnetusers (Id char (+) primary key,email varchar () NULL comment ' user mailbox ', emailconfirmed bit not null comment ' Authentication mailbox ', PasswordHash varchar (+) NULL comment ' account password ', Securitystamp varchar (+) NULL comment ' security stamp ', PhoneNumber varchar (+) NULL comment ' user phone ', phonenumberconfirmed bit not null comment ' authentication phone ', twofactorenabled bit not null comment ' Whether to enable two-factor authentication ', LOCKOUTENDDATEUTC datetime null comment ' Lockout end time ', lockoutenabled bit not null comment ' Enable lock ', Accessfailedcount int NOT null comment ' login failures ', UserName varchar (NOT null comment ' user name ') Comment ' user table '; CREATE Table A Spnetuserclaims (Id int auto_increment primary Key,userid char (+) NOT null comment ' user Id ', ClaimType varchar (+) NULL comm Ent ' claimtype ', claimvalue varchar (+) NULL comment ' claimvalue ') Comment ' claims table '; CREATE TABLE Aspnetuserlogins ( UserId char (+) NOT null comment ", Providerkey varchar (+) NOT null comment", Loginprovider varchar (+) NOT null comme NT ') Comment ' login log table '; CREATE TABLE Aspnetuserroles (USerid char (+) NOT null comment ', Roleid char (+) NOT null comment ') Comment ' User Role table '; CREATE table Aspnetroles (Id char (3 2) Primary key,name varchar (+) NOT null comment ') Comment ' User Role table ';

Step Three: Modify the default assignment of ID, default is 36 GUID, modify to 32 bit

    public class Applicationuser:identityuser    {public        applicationuser ()        } {this            . Id = System.Guid.NewGuid (). ToString ("N");        }        Public async task<claimsidentity> Generateuseridentityasync (usermanager<applicationuser> manager)        {            //Note that AuthenticationType must match            var useridentity = for the corresponding item defined in Cookieauthenticationoptions.authenticationtype Await manager. Createidentityasync (this, defaultauthenticationtypes.applicationcookie);            Add custom user declaration here            return useridentity;}    }

The fourth step: User Login, two sets of code (set is the default mode of login, one set is a custom login method)

The default login method code is as follows:

[Httppost]public Async task<actionresult> Login (string account, string password) {    //1. Using ASP. Identity gets the user object    var = await usermanager.findasync (account, password);    if (user = = null)        return Json (new {Flag = false, Content = "username or password Error!!!") " });    2. Use the ASP. NET identity    to obtain the identity object var identity = await Usermanager.createidentityasync (user, Defaultauthenticationtypes.applicationcookie);    3. Login    Authenticationmanager.signin (new Authenticationproperties () {ispersistent = true}, identity) with the identity object you got above ;    Return Json (New {Flag = true, Content = "Login successful!!!" " });}

The custom login method code is as follows:

[Httppost]public Async task<actionresult> Login (string account, string password) {//1. Get user objects with ASP.    var user = await Usermanager.findasync (account, password); if (user = = null) return Json (new {Flag = false, Content = "username or password Error!!!")    " }); Verify that the user password and login password are consistent, Findemail and other methods use//UserManager.PasswordHasher.VerifyHashedPassword (user.    PasswordHash, password); 2.    Use the ASP. NET identity to obtain the identity object var claims = new list<system.security.claims.claim> (); Claims. ADD (New System.Security.Claims.Claim (System.Security.Claims.ClaimTypes.NameIdentifier, user.    ID)); Claims. ADD (New System.Security.Claims.Claim (System.Security.Claims.ClaimTypes.Name, user.    UserName)); Claims. ADD (New System.Security.Claims.Claim ("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/    Identityprovider "," ASP. "); Claims. ADD (New System.Security.Claims.Claim ("AspNet.Identity.SecurityStamp", user.        Securitystamp)); Here you can customize roles or other data//ClaiMs.    ADD (New System.Security.Claims.Claim (System.Security.Claims.ClaimTypes.Role, "user"));    Claims authentication method var identity = new System.Security.Claims.ClaimsIdentity ("Applicationcookie"); Identity.    Addclaims (claims); 3.    Login Authenticationmanager.signin (new Authenticationproperties () {ispersistent = true}, identity) with the identity object you have received above; Return Json (New {Flag = true, Content = "Login successful!!!" " });}

The fifth step: User registration, two sets of code (set is the default method of registration, a set of custom registration method)

The default registration method code is as follows:

[Httppost]public async task<actionresult> Register (Models.registerviewmodel model) {    var user = new ApplicationUser {UserName = model. UserName, Email = model. Email};    var result = await Usermanager.createasync (user, model. Password);    if (result. Succeeded)    {        return Json (new {Flag = true, Content = "Registered successfully!!! "}, Jsonrequestbehavior.allowget);    }    else    {        return Json (new {Flag = false, Content = "Registration failed!!! "}, Jsonrequestbehavior.allowget);}    }

The custom registration method code is as follows:

[Httppost]public async task<actionresult> Register (Models.registerviewmodel model) {    var db = new Data.datacontext ();    Db. Members.add (New Data.DomainModels.Member ()    {        Id = Guid.NewGuid (). ToString ("N"),        Securitystamp = Guid.NewGuid (). ToString (),        Email = model. Email,        PasswordHash = UserManager.PasswordHasher.HashPassword (model. Password),        UserName = model. UserName    });    var result = await db. Savechangesasync ();    if (Result > 0)    {        return Json (new {Flag = true, Content = "Registration Successful!!! "}, Jsonrequestbehavior.allowget);    }    else    {        return Json (new {Flag = false, Content = "Registration failed!!! "}, Jsonrequestbehavior.allowget);}    }

Well, to here we have completed the login registration function in the background, the code after the extraction, and then see is not very simple appearance, with the previous forms authentication code structure almost, packaging and packaging used up more convenient!

Elasticsearch Full Text Search analysis of the basic operation of the Index series (IV.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.