1. What is asp.net Identity
asp.net Identity is a component that Microsoft has introduced to manage users in asp.net applications.
The mainstay for user management in recent years has been asp.net, membership which has. The biggest limitation is this schema used to store the data worked only with SQL Server and being difficult to extend W Ithout re-implementing A lot of provider classes. The schema itself is overly complex, which made it harder to implement changes the IT than should.
--pro asp.net MVC 5 Platform
2. How to configure ASP.net identity with MySQL 2.1 configuration asp.net identity 2.1.1 Install the appropriate component package
Microsoft.AspNet.Identity.EntityFramework
Microsoft.AspNet.Identity.OWIN
Microsoft.Owin.Host.SystemWeb
2.1.2 Custom Core Components
$ User Model
The default user model is Identityuser (Microsoft.AspNet.Identity.EntityFramework). This class has 12 built-in properties, such as Id, UserName, passwordhash, email, etc.
In general, depending on the business requirements, we need additional attributes. We can create a custom class that inherits from Identityuser and add additional attributes to the custom class.
Using Microsoft.AspNet.Identity.EntityFramework public
class Appuser:identityuser {
//Add additional properties here
}
$ DB Context
Generally we need to change the name of the database table used by the identity. The default database tables are: Aspnetusers, Aspnetuserroles, Aspnetuserlogins, Aspnetusercliams, Aspnetroles.
Using System.Data.Entity;
Using Microsoft.Asp.Net.Identity.EntityFramework;
public class Appidentitydbcontext:identitydbcontext<appuser> {public
appidentitydbcontext (): Base (" Identitydb ") {} public
Appidentitydbcontext (string connectionString)
: Base (connectionString) {
}
protected override void Onmodelcreating (Dbmodelbuilder modelbuilder {
base. Onmodelcreating (ModelBuilder);
Modelbuilder.entity<appuser> (). ToTable ("user");
Modelbuilder.entity<identityrole> (). ToTable ("role");
Modelbuilder.entity<identityuserrole> (). ToTable ("Userrole");
Modelbuilder.entity<identityuserclaim> (). ToTable ("Userclaim");
Modelbuilder.entity<identituuserlogin> (). ToTable ("Userlogin");
}
$ DB Initialization
If you are unfamiliar with the structure of the Identity database table, you can make the identity automatically created by code.
If you are familiar with, I recommend to use a professional database management tools to create, such as MySQL Workbench.
code example. The general initialization code only needs to be executed once, and the policy is carefully considered to prevent the data from being deleted.
Using System.Data.Entity;
public class Appidentitydbcontext:identitydbcontext<appuser> {
...
Static Appidentitydbcontext () {
database.setinitializer<appidentitydbcontext> (new Identitydbinit ());
}
}
Using System.Data.Entity;
Using Microsoft.AspNet.Identity;
Using Microsoft.AspNet.Identity.EntityFramework; public class Identitydbinit:dropcreatedatabasealways<appidentitydbcontext> {protectedd override void Seed (App Identitydbcontext context) {this.
Initadmin (context); Base.
Seed (context);
The public void Initadmin (Appidentitydbcontext context) {string adminname = "admin";
String AdminPassword = "Changeme";
String adminrolename = "Administrators"; Create user usermanager<appuser> Usermanager = new usermanager<appuser> (New Userstore<appu
Ser> (context));
var user = new Appuser {UserName = adminname};
Usermanager.create (user, AdminPassword); Create role rolemanager<identityrole> rolemanager = new rolemanager<identityrole> (New Rolesto
Re<identityrole> (context)); var adminrole = rolemanager.create (new identityrole (adminRoleName)); Give the user a role usermanager.addtorole.
Id, Adminrolename); }
}
$ configuration
Using Microsoft.AspNet.Identity;
Using Microsoft.AspNet.Identity.EntityFramework;
Using Microsoft.AspNet.Identity.Owin;
Using Microsoft.owin;
Using Microsoft.Owin.Security.Cookies;
Using Owin; public class Identityconfig {public void Configuration (Iappbuilder app) {app.
Createperowincontext<appidentitydbcontext> (() => new Appidentitydbcontext ()); App. Createperowincontext<usermanager<appuser>> ((o, c) => new usermanager<appuser> (New UserSt
Ore<appuser> (C.get<appidentitydbcontext> ())); App. Createperowincontext<rolemanager<identityrole>> ((o, c) => new rolemanager<identityrole> (
New Rolestore<identityrole> (C.get<appidentitydbcontext> ())); App. Usecookieauthentication (new cookieauthenticationoptions {AuthenticationType = Defaultauthenticationtypes.appl Icationcookie, Loginpath = new PathString ("/acCount/login ")}); }
}
2.1.3 Configuration Web.config
<configuration>
<appSettings>
<add key= "Owin:appstartup" value= "Identityconfig"/>
...
</appSettings> ...
</configuration>
2.2 Configuring MySQL DB 2.2.1 Install the appropriate component pack
MySql.Data.Entity
2.2.2 Configuration Web.config
<configuration> <configSections> <section name= "entityframework" type= "system.data.entity.i Nternal. Configfile.entityframeworksection, entityframework "> </configSections> <system.data> <dbprovider factories> <remove invariant= "MySql.Data.MySqlClient"/> <add "MySql Data name=" Provider Nt= "MySql.Data.MySqlClient" description= ". Net Framework Data Provider for MySql" type= "MySql.Data.MySqlClient.My SqlClientFactory, Mysql.data "/> </DbProviderFactories> </system.data> <connectionStrings> & Lt;add name= "Identitydb" connectionstring= "Server=192.168.0.9;user id=tester;password=changeme;database= Identitydb "providername=" MySql.Data.MySqlClient "/> </connectionStrings> <entityFramework> < providers> <provider invariantname= "MySql.Data.MySqlClient" type= " MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6 "/> </providers> </entityFramework> </configuration>
2.2.3 Create DB
Method One: Create an empty db without a table, and let identity automatically create the table by code. (see above)
Method Two: Create a DB with all identity related tables
$ User
CREATE TABLE ' user ' (
' Id ' varchar (128) NOT NULL,
' Email ' varchar (256) DEFAULT NULL,
' emailconfirmed ' tinyint (1) Not NULL,
' PasswordHash ' longtext,
' Securitystamp ' longtext,
' PhoneNumber ' longtext,
' Phonenumberconfirmed ' tinyint (1) NOT NULL,
' twofactorenabled ' tinyint (1) is not NULL,
' LOCKOUTENDDATEUTC ' DateTime DEFAULT NULL,
' lockoutenabled ' tinyint (1) NOT NULL,
' accessfailedcount ' int (one) not NULL,
' UserName ' varchar (256) not NULL,
PRIMARY KEY (' Id ')
) Engine=innodb DEFAULT Charset=utf8
$ role
CREATE TABLE ' role ' (
' id ' varchar (128) isn't null,
' Name ' varchar (256) NOT NULL,
PRIMARY KEY (' id ')
) Engin E=innodb DEFAULT Charset=utf8
$ userrole
CREATE TABLE ' userrole ' (
' UserId ' varchar (128) NOT NULL,
' roleid ' varchar (128) is not NULL,
PRIMARY KEY (' Useri d ', ' Roleid '),
key ' identityrole_users ' (' Roleid '),
CONSTRAINT ' appuser_roles ' FOREIGN KEY (' UserId ') REFERENCES ' user ' (' Id ')
on the DELETE CASCADE on UPDATE NO ACTION,
CONSTRAINT ' identityrole_users ' FOREIGN KEY (' Rol EId ') REFERENCES ' role ' (' Id ') on the
DELETE CASCADE on UPDATE NO ACTION
) engine=innodb DEFAULT Charset=utf8
$ userclaim
CREATE TABLE ' Userclaim ' (
' Id ' int () NOT NULL auto_increment,
' UserId ' varchar (128) NOT NULL,
' ClaimType ' Longtext,
' Claimvalue ' Longtext,
PRIMARY key (' id '),
UNIQUE key ' id ' (' id '),
key ' UserId ' (' UserId '), C7/>constraint ' Appuser_claims ' FOREIGN KEY (' UserId ') REFERENCES ' user ' (' Id ') on the
DELETE CASCADE on UPDATE NO action< c9/>) Engine=innodb DEFAULT Charset=utf8
$ userlogin
CREATE TABLE ' userlogin ' (
' loginprovider ' varchar (128) NOT NULL,
' providerkey ' varchar (128) is not NULL,
' UserId ' varchar (128) Not NULL,
PRIMARY key (' Loginprovider ', ' providerkey ', ' UserId '),
key ' Appuser_logins ' ( ' UserId '),
CONSTRAINT ' appuser_logins ' FOREIGN KEY (' UserId ') REFERENCES ' user ' (' Id ') on the
DELETE CASCADE on UPD ATE NO ACTION
) engine=innodb DEFAULT Charset=utf8
3. How to use asp.net Identity 3.1 authentication (authenticate)
using System.Security.Claims; using system.web; using SYSTEM.WEB.MVC; using Microsoft.AspNet.Identity
;
Using Microsoft.AspNet.Identity.Owin; public class Accountcontroller:controller {[HttpPost] [allowanonymous] [Validateantiforgerytoken] Publi C ActionResult Login (string name, string password, string returnurl) {var Usermanager = Httpcontext.getowincontex T ().
Getusermanager<usermanager<appuser>> (); var AuthManager = Httpcontext.getowincontext ().
authentication;
var user = Usermanager.find (name, password); if (user = null) {//Invalid name or password} else {claimsidentity identity =
Usermanager.createidentity (user, Defaultauthenticationtypes.applicationcookie);
Authmanager.signout ();
Authmanager.signin (identity);
Return Redirect (ReturnUrl);
return View (); }
}
3.2 User Actions
Using System.Security.Principal;
Using System.Web;
Using Microsoft.AspNet.Identity;
Using Microsoft.AspNet.Identity.Owin;
var Usermanager = HttpContext.Current.GetOwinContext ()
. Getusermanager<usermanager<appuser>> ();
Gets the current user
IPrincipal principal = HttpContext.Current.User;
Appuser user = Usermanager.findbyname (principal. Identity.name);
Create User
var newuser = new Appuser {UserName = "Alice"};
Varr password = "changeme";
Usermanager.create (newuser, password);
Delete User
Usermanager.delete (users);
Modify user information users
. Email = "huangc126@126.com";
User. PasswordHash = UserManager.PasswordHasher.HashPassword ("secret");
3.3 Role Management
Using System.Web;
Using Microsoft.AspNet.Identity;
Using Microsoft.AspNet.Identity.EntityFramework;
Using Microsoft.AspNet.Identity.Owin;
var rolemanager = HttpContext.Current.GetOwinContext ()
. Getusermanager<rolemanager<identityrole>> ();
Create role
var newrole = new Identityrole {Name = ' Admin '};
Rolemanager.create (newrole);
Give the user
Usermanager.addtorole (userId, Role: "Admin");
Remove the user's role
usermanager.removefromrole (userId, Roles: "Admin");
Delete roles
var role = Rolemanager.findbyname ("Admin");
Rolemanager.delete (role);
3.4 Authorization (Authorization) 3.4.1 role-based Authorization
Using System.Web.Mv;
[Authorize (Roles = "Administrators")]
public class Admincontroller:controller {
...
}
3.4.2 Authorization based on Declaration (Claim)
Using System.Security.Claims;
Using System.Web;
Using SYSTEM.WEB.MVC;
[Claimsaccess (issuer = "Remoteclaims", ClaimType = claimtypes.postalcode, Value = "123456")]
Public ActionResult Action () {
...
}
public class Claimsaccessattribute:authorizeattribute {public
string issuer {get; set;}
public string ClaimType {get; set;}
public string Value {get; set;}
protected override bool Authorizecore (HttpContextBase context) {return context
. User.Identity.IsAuthenticated
&& context. User.Identity is claimsidentity
&& (claimnsidentity) context. user.identity). Hasclaim (
c => C.issuer = = this. Issuer
&& C.type = = this. ClaimType
&& C.value = = this. Value);
}
4. Summary
The
asp.net identity is flexible and supports a variety of extensions that are sufficient for small to medium systems. Although it may look a bit troublesome, even small systems, I suggest using identity. Because it is too troublesome and easy to make mistakes. We should devote more effort to the implementation of the business, rather than to dig up the underlying technical details. Size: 14.7 KB size: 5.5 KB size: 4.9 KB size: 6.6 KB Size: 5.6 KB size: 24.6 KB View picture attachment