Asp.Net MVC 登錄驗證:
1. Windows身份認證,主要用於Intranet上域環境。使用Windows驗證時,用戶的Windows安全令牌在用戶訪問整個網站期間使用HTTP請求,進行消息發送。應用程序會使用這個令牌在本地(或者域)里驗證用戶賬號的有效性,也會評估用戶所在角色所具備的權限。當用戶驗證失敗或者未授權時,瀏覽器就會定向到特定的頁面讓用戶輸入自己的安全憑證(用戶名和密碼)。
Windows身份認證的局限性非常明顯,一旦用戶有超出本地域控制器范圍的外網用戶訪問網站,就會出現問題
2. Forms身份認證,應用於Internet。ASP.NET需要驗證加密的HTTP cookie或者查詢字符串來識別用戶的所有請求。cookie與ASP.NET會話機制(session)的關系密切,在會話超時或者用戶關閉瀏覽器之后,會話和cookie就會失效,用戶需要重新登錄網站建立新的會話。
3. ASP.NET Identity - Claims-based(基於聲明)的身份認證: 對比Windows認證和Forms身份認證,claims-based認證這種方式將認證和授權與登錄代碼分開,將認證和授權拆分成另外的web服務。類似於使用的是第三方的登錄系統,如微信登錄。
使用Forms身份驗證流程:
一. 配置:
<authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2000"> </forms> </authentication>
二、用戶登錄
1、用戶名密碼驗證。
2、驗證成功,取出部分必要的用戶信息usedata,序列化成string.
3. 創建FormsAuthenticationTicket 票據,將usedata放入其中。
public void SetCookie(string source) { var ticket = new FormsAuthenticationTicket(1, "loginuser", DateTime.Now, DateTime.Now.AddDays(10), false, source); string authTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie("hanApp", authTicket); Response.Cookies.Remove(cookie.Name); Response.Cookies.Add(cookie); //HttpCookie signCookie = new HttpCookie("hanApp_sign", "1 "); //Response.Cookies.Remove(signCookie.Name); //Response.Cookies.Add(signCookie); }
4. 調用FormsAuthentication.Encrypt對票據信息進行加密。
5. 創建HttpCookie,並通過Response.Cookies.Add將cookie發回到前端。
6. Redirect跳轉到登錄前的頁面。
三. 一般驗證:
1. 對於一般的controller和action,可以有直接使用Authorize Attribute,那么訪問他們之前會自動驗證是否登錄。
2. 我們也可以自定義一個attribute來實現這個邏輯,只要這個attribute繼承AuthorizeAttribute, 或者自己繼承ActionFilterAttribute並重寫OnActionExecuting方法,即可。
3. 我們可以在全局增加驗證操作,就不需要在每個controller上增加這個attribute. 如下:
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new AuthorizeAttribute()); filters.Add(new ActionExceptionAttribute()); }
3. 對於部分不需要進行 驗證的action,可以使用AllowAnonymous attribute。
[AllowAnonymous] public ActionResult Login(s) { ..... return View(); }
Claims-based(基於聲明)的身份認證,
先來看一下代碼,直觀感受一下,如何使用Claims-based(基於聲明)的身份認證:
private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } private async Task SignInAsync() { // 1. 利用ASP.NET Identity獲取用戶對象 var user = await UserManager.FindAsync("UserName", "Password"); // 2. 利用ASP.NET Identity獲取identity 對象 ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); // 3. 結合OWIN,引用 Microsoft.Owin.Security命名空間,實現IIS與web應用的解耦 AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity); }
下面這篇文章介紹了如何使用第三方的應用進進登錄:http://www.cnblogs.com/clark159/p/5195673.html?utm_source=tuicool&utm_medium=referral