关于Identity的使用
先感谢自己,并没有因为identity的资料太少、封装太多而放弃他,自己去写一个登录、权限的框架。
既然遇到了,那就拿下他。
我们知道,创建一个MVC项目的时候,有一个地方让我们选身份验证,选择个人身份验证,就是我们下面要讲的identity了。

与identity相关的文件有这几个:
1、Models->IdentityModels
2、App_Start->IdentityConfig
3、App_Start->Startup.Auth
一个一个看吧,IdentityModels:
public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // 请注意,authenticationType 必须与 CookieAuthenticationOptions.AuthenticationType 中定义的相应项匹配 var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // 在此处添加自定义用户声明 return userIdentity; } /// <summary> /// 在这里可以添加Identity保留字段以外的字段 /// 例如:别名 /// </summary> public string OtherName { get; set; } /// <summary> /// 性别 /// 为了尊重人妖,性别也可以设计为int或varchar,毕竟bit是比较难以存储ladyBoy的 /// </summary> public bool Sex { get; set; } }
ApplicationUser 继承了IdentityUser
public class IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser, IUser<string> { public IdentityUser(); public IdentityUser(string userName); }
IdentityUser 又继承了IdentityUser
public class IdentityUser<TKey, TLogin, TRole, TClaim> : IUser<TKey> where TLogin : Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<TKey> where TRole : Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<TKey> where TClaim : Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<TKey> { public IdentityUser(); public virtual int AccessFailedCount { get; set; } public virtual ICollection<TClaim> Claims { get; } public virtual string Email { get; set; } public virtual bool EmailConfirmed { get; set; } public virtual TKey Id { get; set; } public virtual bool LockoutEnabled { get; set; } public virtual DateTime? LockoutEndDateUtc { get; set; } public virtual ICollection<TLogin> Logins { get; } public virtual string PasswordHash { get; set; } public virtual string PhoneNumber { get; set; } public virtual bool PhoneNumberConfirmed { get; set; } public virtual ICollection<TRole> Roles { get; } public virtual string SecurityStamp { get; set; } public virtual bool TwoFactorEnabled { get; set; } public virtual string UserName { get; set; } }
IdentityUser+IdentityUser,就是identity框架为我们保留的一些用户信息字段。
IdentityModels还有一个属性是:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("IdentityDemo", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } }
这个大家应该比较熟悉了,是EF中的上下文。IdentityDemo是webconfig中的数据库连接字符串,如果不写,默认叫ApplicationDbContext。
ApplicationUser是用户模型,IdentityDbContext<ApplicationUser>的代码:
public class IdentityDbContext<TUser> : IdentityDbContext<TUser, IdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim> where TUser : Microsoft.AspNet.Identity.EntityFramework.IdentityUser { public IdentityDbContext(); public IdentityDbContext(string nameOrConnectionString); public IdentityDbContext(string nameOrConnectionString, bool throwIfV1Schema); public IdentityDbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection); }
public class IdentityDbContext<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim> : DbContext where TUser : Microsoft.AspNet.Identity.EntityFramework.IdentityUser<TKey, TUserLogin, TUserRole, TUserClaim> where TRole : Microsoft.AspNet.Identity.EntityFramework.IdentityRole<TKey, TUserRole> where TUserLogin : Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<TKey> where TUserRole : Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<TKey> where TUserClaim : Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<TKey> { public IdentityDbContext(); public IdentityDbContext(string nameOrConnectionString); public IdentityDbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection); public bool RequireUniqueEmail { get; set; } public virtual IDbSet<TRole> Roles { get; set; } public virtual IDbSet<TUser> Users { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder); protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items); }
虽然看不到他们都做了什么,但是能看到,这两个类都继承自DbContext,然后看一下这几个类的属性,IdentityRole,IdentityUserLogin, IdentityUserRole, IdentityUserClaim。
因为我已经试了一遍了,根据建好的数据库反推,应该是创建了这几张表,但是并没有什么卵用,我还是不知道这几个是干嘛的。
总结一下这个文件:1、可以自己增加用户表的字段。2、可以自己配置数据库连接
IdentityConfig,核心配置都在这里了:
由于本人比较懒,就不一 一贴代码了,有以下几块:
1、配置发邮件。
2、配置发sms短信
3、用户模型管理:在Create中可以配置创建账号时的验证逻辑,当然你不在这里写也可以写在ViewModel中,感觉写在这里有装逼嫌疑。主要是这几个验证:manager.UserValidator,manager.PasswordValidator,等等很多,自己看看就可以了
特别说一下,现在很多网站手机、邮箱、用户名都可以登录,manager.RegisterTwoFactorProvider在这里配置即可。
4、登录管理器:
这里牵扯到Claims跟Owin,简单看了一下资料,Claims是跟第三方登录相关的,Owin是解耦应用程序与服务器的。通俗说就是解耦网站与IIS的。
Startup.Auth:看名字就是程序启动时候的身份验证的。里面解释得很详细。就不一一说了。
好了,大概就是这么几个文件。
下面我们来看AccountController中的注册:
var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password);
填充模型,然后创建数据。
登录:
// 这不会计入到为执行帐户锁定而统计的登录失败次数中 // 若要在多次输入错误密码的情况下触发帐户锁定,请更改为 shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
这个登录是返回true或者flase,如果你需要修改登录以后的信息,比如登录几次了,最后一次登录时间,就换一个登录方法:
var user = await UserManager.FindAsync(model.Email, model.Password);
这个返回的是一个用户模型。你就可以修改数据了。
UserManage有很多方法,每个都自己去试一下就知道是干嘛的了。
var aa = await UserManager.FindByEmailAsync(model.Email); var bb = await UserManager.FindByNameAsync(model.Email);
好了,注册、登录都可以了。看一下数据库吧:

当然,我们对这么垃圾的表命名是非常反感的。而且我找了半天竟然没有地方改。怎么办呢?看来只能扩展identity了。

浙公网安备 33010602011771号