ASP.NET WebAPI 中引入了新的一套身份驗證和授權的機制,官方的叫法是ASP.NET Identity,有關這個概念的細節,感興趣的同學可以參考 http://www.asp.net/identity
這套新的機制,默認還是使用SQL Server來做身份保存的,但更多的是提供了靈活性,包括與外部驗證系統(OAuth)的整合。但在一些較為簡單的場合下,我們可能希望簡化這個部分,例如我們不需要外部整合,而且我們的用戶數也相對有限,不希望用數據庫來實現。
本文提供了一個實例,我是使用XML文件的方式來保存用戶信息的,該文件的格式大致如下
然后,我編寫了一個自定義的類型,實現了一些主要的方法
public class XmlUserStore : IUserStore<ApplicationUser>,IUserPasswordStore<ApplicationUser>,IRoleStore<IdentityRole> { private string filePath = HttpContext.Current.Server.MapPath("~/app_data/users.xml"); public Task CreateAsync(ApplicationUser user) { throw new System.NotImplementedException(); } public Task DeleteAsync(ApplicationUser user) { throw new System.NotImplementedException(); } public Task<ApplicationUser> FindByIdAsync(string userId) { return FindByNameAsync(userId); } public Task<ApplicationUser> FindByNameAsync(string userName) { var doc = XDocument.Load(filePath); var found = doc.Root.Elements("user").FirstOrDefault(x => x.Attribute("name").Value == userName); ApplicationUser user = null; if (found != null) { user = new ApplicationUser() { UserName = userName, Id = userName, PasswordHash = found.Attribute("password").Value }; } return Task<ApplicationUser>.FromResult(user); } public Task UpdateAsync(ApplicationUser user) { return Task.FromResult(0); } public void Dispose() { } public Task<string> GetPasswordHashAsync(ApplicationUser user) { var result = string.Empty; if (user != null) result = user.PasswordHash; return Task<string>.FromResult(result); } public Task<bool> HasPasswordAsync(ApplicationUser user) { throw new System.NotImplementedException(); } public Task SetPasswordHashAsync(ApplicationUser user, string passwordHash) { var doc = XDocument.Load(filePath); var found = doc.Root.Elements("user").FirstOrDefault(x => x.Attribute("name").Value ==user.UserName); if(found!=null) { found.Attribute("password").Value = passwordHash; doc.Save(filePath); return Task.FromResult(1); } return Task.FromResult(0); } public Task CreateAsync(IdentityRole role) { throw new System.NotImplementedException(); } public Task DeleteAsync(IdentityRole role) { throw new System.NotImplementedException(); } Task<IdentityRole> IRoleStore<IdentityRole>.FindByIdAsync(string roleId) { throw new System.NotImplementedException(); } Task<IdentityRole> IRoleStore<IdentityRole>.FindByNameAsync(string roleName) { throw new System.NotImplementedException(); } public Task UpdateAsync(IdentityRole role) { throw new System.NotImplementedException(); } }
接下來,我們要在AccountController中使用這個新的UserStore的類型。


