注意,Microsoft.AspNet.Identity.Core.1.0.0和Microsoft.AspNet.Identity.Core.2.2.1差别太大,需考虑实际项目中用的是哪种,本文是基于2.2.1来写的!!
两个概念:1、OWIN的英文全称是Open Web Interface for .NET。2、Microsoft.AspNet.Identity是微软在MVC 5.0中新引入的一种membership框架,和之前ASP.NET传统的membership以及WebPage所带来的SimpleMembership(在MVC 4中使用)都有所不同。本文以自定义数据库表来实现用户的登录授权。不依赖MemberShip和EF框架。
要实现自定义,有三处需重写:UserStore、PasswordHasher、IUser
自定义UserStore:
继承微软的UserStore并重新实现它的FindByIdAsync、FindByNameAsync等方法。
为什么要这么做?
1、替换EF并换成我们自己的底层ORM(我在另一篇文章中用EF写了一套)
2、多个Area可以自定义多个UserStore,不同的Area可以访问不同的UserStore,当然多个Area访问同一个UserStore也是可以。
它是如何工作的?

public class UserManager<TUser> : IDisposable where TUser: IUser { private ClaimsIdentityFactory<TUser> _claimsFactory; private bool _disposed; private IPasswordHasher _passwordHasher; private IIdentityValidator<string> _passwordValidator; private IIdentityValidator<TUser> _userValidator; public UserManager(IUserStore<TUser> store) { if (store == null) { throw new ArgumentNullException("store"); } this.Store = store; this.UserValidator = new UserValidator<TUser>((UserManager<TUser>) this); this.PasswordValidator = new MinimumLengthValidator(6); this.PasswordHasher = new Microsoft.AspNet.Identity.PasswordHasher(); this.ClaimsIdentityFactory = new ClaimsIdentityFactory<TUser>(); }
通过UserManager的源代码可以看到,UserManager运用了桥接模式,查找用户的方法来自UserStore,返回的是泛型
自定义IUserIdentity:
1、需注意,此处可不是继承IUserIdentity,IUserIdentity需和IdentityDbContext配合,我们既然用自己的ORM,就等于放弃IdentityDbContext。

namespace Biz.Framework.AspNet.Identity { /// <summary> /// IdentityLoginUser,重写Identity.IUser,这个跟数据库中的用户表是两码事,专门做登录、权限判断用的 /// 但是,我们可以把它跟数据库的用户表结合起来用,上面部分为数据的用户表,下面为继承成IUserIdentity(可做公司产品) /// </summary> [Serializable] public class IdentityLoginUser : ISerializable, IUserIdentity, Microsoft.AspNet.Identity.IUser { #region 数据库字段 public int UserId { get; set; } public string UserName { get; set; } public string Password { get; set; } #endregion #region 公司自己的产品IUserIdentity接口 bool? IUserIdentity.IsRootAdmin { get { return null; } } #endregion #region 微软IUser接口 string Microsoft.AspNet.Identity.IUser<string>.Id { get { return null; } } #endregion #region 必须实现,否则无法使用 [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("UserId", this.UserId); info.AddValue("Password", string.Empty); } /// <summary> /// 反序列化的构造函数 /// </summary> /// <param name="info"></param> /// <param name="context"></param> public IdentityLoginUser(SerializationInfo info, StreamingContext context) { this.UserId = info.GetInt32("UserId"); this.Password = info.GetString("Password"); } #endregion public string ToJson() { return JsonConvert.SerializeObject(this); } } }
2、微软自带的User字段肯定是不符合实际环境的字段
自定义UserStore,整体代码如下

using Biz.DBUtility;//这个是自己的底层ORM,可以是EF的edmx或者其他 using Microsoft.AspNet.Identity; using System; using System.Data.Entity; using System.Threading.Tasks; namespace Biz.Framework.AspNet.Identity { /// <summary> /// 针对不同的Area,可以定义多个UserStore。 /// TODO:可以支持多种形式的用户读取吗?比如AD,接口验证等?待研究 /// </summary> public class BizUserStore : IUserPasswordStore<IdentityLoginUser>, IUserStore<IdentityLoginUser>, IDisposable { public Task CreateAsync(IdentityLoginUser user) { throw new NotImplementedException("不支持新增用户"); } public Task DeleteAsync(IdentityLoginUser user) { throw new NotImplementedException("不支持删除用户"); } public Task<IdentityLoginUser> FindByIdAsync(int userId) { //BizEntities b = new BizEntities(); return null;//b.Sys_User.FindAsync(new object[] { userId }); } public Task<IdentityLoginUser> FindByNameAsync(string userName) { if (string.IsNullOrEmpty(userName)) return null; BizEntities dbContext = new BizEntities(); Sys_User user = dbContext.Sys_User.FirstOrDefaultAsync(q => q.UserName == userName).Result; IdentityLoginUser identityLoginUser = new IdentityLoginUser { UserId = user.UserId, UserName = user.UserName, Password = user.Password }; return Task.FromResult<IdentityLoginUser>(identityLoginUser); } public Task UpdateAsync(IdentityLoginUser user) { throw new NotImplementedException("不支持删除用户"); } public Task<IdentityLoginUser> FindByIdAsync(string userId) { if (string.IsNullOrEmpty(userId)) return null; return this.FindByIdAsync(int.Parse(userId)); } public void Dispose() { } #region IUserPasswordStore接口 /// <summary> /// 这个方法用不到!!! /// 虽然对于普通系统的明文方式这些用不到。 /// 但是!!!MVC5之后的Identity2.0后数据库保存的密码是加密盐加密过的,这里也需要一并处理,然而1.0并不需要处理,需注意!!! /// </summary> /// <param name="user"></param> /// <returns></returns> public Task<string> GetPasswordHashAsync(IdentityLoginUser user) { return Task.FromResult<string>(user.Password); } public Task<bool> HasPasswordAsync(IdentityLoginUser user) { return Task.FromResult<bool>(!string.IsNullOrWhiteSpace(user.Password)); } public Task SetPasswordHashAsync(IdentityLoginUser user, string passwordHash) { user.Password = passwordHash; return Task.FromResult<int>(0); } #endregion } }
但是,此时运行代码会报错:Base-64 字符数组或字符串的长度无效。这个是由于微软的UserManager下的IPasswordHasher是通过MD5+随机盐加密出来的。所以,我们还要将密码加密,对比这一套换成我们自己的!你也可以自己去研究一下加密盐,我看微软的源代码是没看懂啦,我以为盐既然是随机生成的,应该是放在数据库里啊,但是数据库里没有,不懂!
自定义PasswordHasher,用自己的密码

using Microsoft.AspNet.Identity; namespace Biz.Framework.AspNet.Identity { public class BizPasswordHasher : PasswordHasher { /// <summary> /// 加密密码,可以采用简单的MD5加密,也可以通过MD5+随机盐加密 /// </summary> /// <param name="password"></param> /// <returns></returns> public override string HashPassword(string password) { return password; } public override PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword) { //此处什么加密都不做! if (hashedPassword == providedPassword) //if (Crypto.VerifyHashedPassword(hashedPassword, providedPassword)) { return PasswordVerificationResult.Success; } return PasswordVerificationResult.Failed; } } }

namespace Biz.Web.Controllers { [Authorize] public class AccountController : Controller { public AccountController() : this(new UserManager<IdentityLoginUser>(new BizUserStore())) { } public AccountController(UserManager<IdentityLoginUser> userManager) { UserManager = userManager; userManager.PasswordHasher = new BizPasswordHasher(); }
但是,判断用户通过后,登录代码又报错:System.ArgumentNullException: 值不能为 null。重写ClaimsIdentityFactory后发现是User.Id为null,有次IdentityLogin中继承自IUser的Id必须赋值,可以用用户表中的UserId。

using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; namespace Biz.Framework.AspNet.Identity { //public class BizClaimsIdentityFactory<TUser> : IClaimsIdentityFactory<TUser> where TUser : class, IUser public class BizClaimsIdentityFactory<TUser> : ClaimsIdentityFactory<TUser, string> where TUser : class, IUser<string> { internal const string DefaultIdentityProviderClaimValue = "ASP.NET Identity"; internal const string IdentityProviderClaimType = "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider"; public string RoleClaimType { get; set; } public string UserIdClaimType { get; set; } public string UserNameClaimType { get; set; } public BizClaimsIdentityFactory() { this.RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; this.UserIdClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"; this.UserNameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"; } public async override Task<ClaimsIdentity> CreateAsync(UserManager<TUser, string> manager, TUser user, string authenticationType) { if (manager == null) { throw new ArgumentNullException("manager"); } if (user == null) { throw new ArgumentNullException("user"); } ClaimsIdentity id = new ClaimsIdentity(authenticationType, ((BizClaimsIdentityFactory<TUser>)this).UserNameClaimType, ((BizClaimsIdentityFactory<TUser>)this).RoleClaimType); id.AddClaim(new Claim(((BizClaimsIdentityFactory<TUser>)this).UserIdClaimType, user.Id, "http://www.w3.org/2001/XMLSchema#string")); id.AddClaim(new Claim(((BizClaimsIdentityFactory<TUser>)this).UserNameClaimType, user.UserName, "http://www.w3.org/2001/XMLSchema#string")); id.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string")); if (manager.SupportsUserRole) { IList<string> roles = await manager.GetRolesAsync(user.Id); using (IEnumerator<string> enumerator = roles.GetEnumerator()) { while (enumerator.MoveNext()) { string current = enumerator.Current; id.AddClaim(new Claim(((BizClaimsIdentityFactory<TUser>)this).RoleClaimType, current, "http://www.w3.org/2001/XMLSchema#string")); } } } if (manager.SupportsUserClaim) { //ClaimsIdentity identity3; //ClaimsIdentity identity2 = id; //IList<Claim> claims = await manager.GetClaimsAsync(user.Id); //identity3.AddClaims(claims); } return id; } //public async override Task<ClaimsIdentity> CreateAsync(UserManager<TUser> manager, TUser user, string authenticationType) //{ // if (manager == null) // { // throw new ArgumentNullException("manager"); // } // if (user == null) // { // throw new ArgumentNullException("user"); // } // ClaimsIdentity id = new ClaimsIdentity(authenticationType, ((BizClaimsIdentityFactory<TUser>)this).UserNameClaimType, ((BizClaimsIdentityFactory<TUser>)this).RoleClaimType); // id.AddClaim(new Claim(((BizClaimsIdentityFactory<TUser>)this).UserIdClaimType, user.Id, "http://www.w3.org/2001/XMLSchema#string")); // id.AddClaim(new Claim(((BizClaimsIdentityFactory<TUser>)this).UserNameClaimType, user.UserName, "http://www.w3.org/2001/XMLSchema#string")); // id.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string")); // if (manager.SupportsUserRole) // { // IList<string> roles = await manager.GetRolesAsync(user.Id); // using (IEnumerator<string> enumerator = roles.GetEnumerator()) // { // while (enumerator.MoveNext()) // { // string current = enumerator.Current; // id.AddClaim(new Claim(((BizClaimsIdentityFactory<TUser>)this).RoleClaimType, current, "http://www.w3.org/2001/XMLSchema#string")); // } // } // } // if (manager.SupportsUserClaim) // { // //ClaimsIdentity identity3; // //ClaimsIdentity identity2 = id; // //IList<Claim> claims = await manager.GetClaimsAsync(user.Id); // //identity3.AddClaims(claims); // } // return id; //} } }
自此,本文结束!需要代码的可留言
其他的一些可借鉴的文章:
加密盐