ASP.NET Identity的基本用法
早在2005年的時候,微軟隨著ASP.NET 推出了membership機制,十年磨一劍,如今的ASP.NET Identity是否足夠強大,一起來體會。
在VS2013下新建項目,選擇"ASP.NET Web應(yīng)用程序。",點擊"確定"。
選擇"MVC"模版。
創(chuàng)建的網(wǎng)站包括三個核心組件:
- 1、Microsoft.AspNet.Identity.EntityFramework
這是基于ASP.NET Identity的Entity Framework實現(xiàn),用來持久化ASP.NET Identity數(shù)據(jù)和架構(gòu),以及負(fù)責(zé)和SQL Server數(shù)據(jù)庫交互。
- 2、Microsoft.AspNet.Identity.Core
包含了ASP.NET Identity的核心接口,用來針對不同的持久層,比如Azure Table Storeage, NoSQL數(shù)據(jù)庫等做不同的實現(xiàn)。
- 3、Microsoft.AspNet.Identity.OWIN
OWIN是一個安全中間件,Microsoft在此基礎(chǔ)上作了再開發(fā),如記錄日志,產(chǎn)生cookie的時候用到。
各組件的依賴關(guān)系如圖:
F5運行項目。
點擊右上角的注冊按鈕,填寫注冊信息,點擊"注冊"按鈕,新用戶注冊成功并呈登錄狀態(tài)。
點擊VS2013的"停止調(diào)試"按鈕。
存儲的數(shù)據(jù)放在了哪呢?
右鍵App_Data,點擊"在文件資源管理器中打開文件",原來數(shù)據(jù)庫被存放在項目文件夾App_Data下了。
如何查看這些數(shù)據(jù)呢?
點擊VS2013的左上角"服務(wù)器資源管理器",右鍵"DefaultConnection",從中可以查看所有的數(shù)據(jù)。
比如用戶數(shù)據(jù)被存放在表"AspNetUsers"中。
點擊"注冊"按鈕,是把請求交給了AcccountController的Register這個Action。
[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Register(RegisterViewModel model){ if (ModelState.IsValid) {var user = new ApplicationUser() { UserName = model.UserName };var result = await UserManager.CreateAsync(user, model.Password);if (result.Succeeded){ await SignInAsync(user, isPersistent: false); return RedirectToAction("Index", "Home");}else{ AddErrors(result);} } // 如果我們進行到這一步時某個地方出錯,則重新顯示表單 return View(model);}
以上,
- 通過ApplicationUser來實例化一個用戶
- 通過UserManager的靜態(tài)、異步方法CreateAsync創(chuàng)建用戶
- 通過異步方法SignInAsync來讓用戶登錄
private async Task SignInAsync(ApplicationUser user, bool isPersistent){ AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);}
以上
- 所有驗證的事交給了AuthenticationManager,負(fù)責(zé)登錄登出
- 把創(chuàng)建ClaimsIdentity交給了UserManager
至于登出,請求交給了AccountController的LogOff。
[HttpPost][ValidateAntiForgeryToken]public ActionResult LogOff(){ AuthenticationManager.SignOut(); return RedirectToAction("Index", "Home");}
還沒有看到ASP.NET Idenity有多少過人之處,讓時間來告訴我們。
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章:
1. ASP.NET MVC使用異步Action的方法2. 使用HttpClient增刪改查ASP.NET Web API服務(wù)3. ASP.NET Core實現(xiàn)中間件的幾種方式4. ASP.NET MVC實現(xiàn)樹形導(dǎo)航菜單5. 使用HttpClient消費ASP.NET Web API服務(wù)案例6. asp.net core項目授權(quán)流程詳解7. ASP.NET Core按用戶等級授權(quán)的方法8. ASP.NET MVC使用Boostrap實現(xiàn)產(chǎn)品展示、查詢、排序、分頁9. asp.net core 認(rèn)證和授權(quán)實例詳解10. asp.net core服務(wù)限制堆內(nèi)存大小的操作方法
