標籤:uname addm 資料加密 應該 認證 分享 使用者 null 技術
最近悟出來一個道理,在這兒分享給大家:學曆代表你的過去,能力代表你的現在,學習代表你的將來。
十年河東十年河西,莫欺少年窮
學無止境,精益求精
最近在做自學MVC,遇到的問題很多,索性一點點總結下。
正題:
做過三層架構的童鞋都知道,如果要驗證/授權一個使用者登入,我們一般採取如下方法:
1、使用者輸入使用者名稱、密碼進行登入
2、賬戶/密碼正確,儲存使用者資訊至Cookies或者Session,跳轉至首頁面
3、在首頁面Page_Load的時候,判斷Cookies或者Session的值,如果Cookies或者Session中存放的值在資料庫驗證成功,則可以觀看首頁面資訊,如果驗證不成功,或者Session/Cookies值為NULL時,直接執行語句:Response.Redirect(../Login.aspx);
上述方法很簡單,功能上也實現了登入的認證與授權,相信很多人寫的項目都會採取此方法進行判斷,殊不知:這種方法安全係數較低,而且違背了NET的登入授權與驗證原則。那麼NET中的授權與驗證又是什麼呢?
.net中的認證(authentication)與授權(authorization)
認證(authentication) 就是 :判斷使用者有沒有登入,使用者輸入的賬戶密碼等資訊是否通過資料庫比對
授權(authorization) 就是:使用者登入後的身份/角色識別,使用者通過認證後<登陸後>我們記錄使用者的資訊並授權
.net中與"認證"對應的是IIdentity介面,而與"授權"對應的則是IPrincipal介面,這二個介面的定義均在命名空間System.Security.Principal中,詳情如下:
使用者認證介面:
using System;using System.Runtime.InteropServices; namespace System.Security.Principal{ [ComVisible(true)] public interface IIdentity { string AuthenticationType { get; } bool IsAuthenticated { get; } string Name { get; } }}
使用者授權介面:
using System;using System.Runtime.InteropServices; namespace System.Security.Principal{ [ComVisible(true)] public interface IPrincipal { IIdentity Identity { get; } bool IsInRole(string role); }}
應該注意到:IPrincipal介面中包含著一個唯讀IIdentity
1、IIdentity 介面中屬性的含義:
AuthenticationType 驗證方式:NET中有Windows、Forms、Passport三種驗證方式,其中以Forms驗證用的最多,本節講解的MVC驗證與授權就是基於Form。
IsAuthenticated 是否通過驗證,布爾值
Name 使用者登入的賬戶名稱
2、IPrincipal 介面中屬性的含義:
IIdentity 上述IIdentity介面的執行個體
IsInRole 布爾值,驗證使用者權限
下面我們對HttpContext.Current.User刨根問底
HttpContext.User本身就是一個IPrincipal介面的執行個體。
有了上面的預備知識,我們在程式中處理認證問題時,只需對HttpContext.User賦值即可。
下面是小弟類比的一個授權方法
/// <summary> /// 類比授權 此處不經過驗證 直接授權訪問 UserCenter() /// </summary> /// <returns></returns> public ActionResult Login() { GenericIdentity _identity = new GenericIdentity("天才臥龍", "Forms"); GenericPrincipal _principal = new GenericPrincipal(_identity, new string[] { "admins", "vips" }); HttpContext.User = _principal; return RedirectToAction("UserCenter"); } [Authorize(Roles = "admins")] public ActionResult UserCenter() { return View(); }
上面的方法中,一旦運行登陸頁,不需要填賬戶密碼,直接會訪問UserCenter(),即:直接會跳轉到個人中心
好啦,如果上邊的例子大家看懂了,那麼下面的登入其實就很簡單了,和上述所講一樣:由於 HttpContext.User 本身就是一個IPrincipal介面的執行個體!因此:我們只需給這個執行個體賦值即可,上面的例子就證實了這一點。
咱們回到開篇的描述,一般我們都是通過Session或者cookies就行Forms驗證登入,那麼在MVC中我們應當怎麼做呢?
1.MVC使用Forms驗證儲存使用者自訂資訊
Forms驗證在內部的機製為把使用者資料加密後儲存在一個基於cookie的票據FormsAuthenticationTicket中,因為是經過特殊加密的,所以應該來說是比較安全的。而.net除了用這個票據存放自己的資訊外,還留了一個地給使用者自由支配,這就是現在要說的UserData。
UserData可以用來儲存string類型的資訊,並且也享受Forms驗證提供的加密保護,當我們需要這些資訊時,也可以通過簡單的get方法得到,兼顧了安全性和易用性,用來儲存一些必須的敏感資訊還是很有用的。
2、FormsAuthenticationTicket基於forms的驗證
構建基於forms的驗證機制過程如下:
1,設定IIS為可匿名訪問和asp.net web.config中設定為form驗證,配置webConfig,如下:
<!--使用者沒有授權時 自動退回登陸介面--> <authentication mode="Forms"> <forms loginUrl="~/Home/Login" timeout="2880" path="/" /> </authentication>
2,檢索資料存放區驗證使用者,並檢索角色(其實就是登入驗證)
3,使用FormsAuthenticationTicket建立一個Cookie並回傳到用戶端,並儲存
關於2、3兩步,我以程式碼範例:
我建立的登入Model如下:
public class UserLogin { private readonly object LOCK = new object(); Maticsoft.BLL.YX_UserInfo Bll = new Maticsoft.BLL.YX_UserInfo(); Maticsoft.Model.YX_UserInfo Mol = new Maticsoft.Model.YX_UserInfo(); // [Required(ErrorMessage = "請輸入賬戶號碼/手機號")] [RegularExpression(@"^1[3458][0-9]{9}$", ErrorMessage = "手機號格式不正確")] public string UserName { get; set; } [Required(ErrorMessage="請輸入賬戶密碼")] [DataType(DataType.Password,ErrorMessage="密碼格式不正確")] [MinLength(6, ErrorMessage = "密碼長度介於6~15位之間")] [MaxLength(15, ErrorMessage = "密碼長度介於6~15位之間")] public string UserPwd { get; set; } public bool LoginAction() { lock (LOCK) { DataTable dt = Bll.GetList(" Uname=‘" + CommonMethod.CheckParamThrow(UserName) + "‘ and Upwd=‘" + CommonMethod.Md532(UserPwd) + "‘ and flat1=1").Tables[0]; if (dt.Rows.Count > 0) { FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, UserName, DateTime.Now, DateTime.Now.AddMinutes(30), false, "admins,vip", "/" ); string encryptedTicket = FormsAuthentication.Encrypt(authTicket); System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); return true; } else { return false; } } } }
上述代碼中
資料庫驗證成功,我們將使用者資訊存入Cookies,
然後我們在Global中解析這個Cookies,然後把解析的結果賦值給:HttpContext.User
代碼如下:
/// <summary> /// 登入驗證、s授權 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Application_AuthenticateRequest(Object sender, EventArgs e) { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch (Exception ex) { return; } string[] roles = authTicket.UserData.Split(‘,‘); FormsIdentity id = new FormsIdentity(authTicket); GenericPrincipal principal = new GenericPrincipal(id, roles); Context.User = principal;//存到HttpContext.User中 }
Context.User一旦被賦值成功,我們就可以訪問那些有許可權限制的方法。代碼如下:
[Authorize(Roles = "admins")] public ActionResult UserCenter() { return View(); }
SO,搞懂了本質,一切都可以解決
講完了,再見--今天請求我鄭州的女友幫我解答,一直沒能聯絡到她人,索性自己琢磨。
@陳臥龍的部落格
MVC 登入認證與授權