ASP.NET的MVC中使用Cookie做身份验证(附代码下载)
場景
ASP.NET的MVC中使用Session做身份驗證(附代碼下載):
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/107181028
在上面使用Session做身份驗證之后,如果網(wǎng)站很熱門,那么使用Session就會造成主機非常大的負擔(dān)。
使用Cookie做身份驗證的主要目的是在于降低主機端的負擔(dān)。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關(guān)注公眾號
霸道的程序猿
獲取編程相關(guān)電子書、教程推送與免費下載。
實現(xiàn)
同上在新建項目時選擇無身份驗證,然后打開HomeController,添加登錄的action
??????? public ActionResult Login(string account, string password){var cookieName = "mvcAuth";//如果用戶名和密碼正確if (account == "mvc" && password == "123456"){//如果已經(jīng)存在這個cookie則將其刪除if (Response.Cookies.AllKeys.Contains(cookieName)){var cookieVal = Response.Cookies[cookieName].Value;HttpContext.Application.Remove(cookieVal);Response.Cookies.Remove(cookieName);}//登錄成功產(chǎn)生一組cookievar token = Guid.NewGuid().ToString();//將 token 存放到 Application 內(nèi)(實際上應(yīng)該存進數(shù)據(jù)庫)HttpContext.Application[token] = DateTime.UtcNow.AddHours(1);//新建一個Cookievar hc = new HttpCookie(cookieName, token){//設(shè)置此Cookie的過期時間Expires = DateTime.Now.AddHours(1),//設(shè)置Cookie是否可以通過客戶端腳本訪問HttpOnly = true};//將Cookie添加到Cookie集合Response.Cookies.Add(hc);}//重定向到indexreturn RedirectToAction("Index");}上面產(chǎn)生一組GUID后存放至Cookie內(nèi),這里使用的是Application對象存放用戶登錄的時間,實際應(yīng)該使用數(shù)據(jù)庫。
因為使用Cookie存放數(shù)據(jù),而這些數(shù)據(jù)只有后端程序代碼才需要訪問,因此強烈建議加上HttpOnly,提高安全性。
再來建立Filters目錄,用來存放自定義驗證邏輯的類,在此目錄下新建類AuthorizePlusAttribute
此類要繼承AuthorizeAttribute,并重寫方法OnAuthorization
注意要添加命名空間
using System.Web.Mvc;AuthorizePlusAttribute類代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc;namespace MVCCookieTest.Filters {public class AuthorizePlusAttribute : AuthorizeAttribute{public override void OnAuthorization(AuthorizationContext filterContext){//獲取Tokenvar token = Convert.ToString(filterContext.HttpContext.Request.Cookies["mvcAuth"].Value);//如果token為空 丟回401if (string.IsNullOrWhiteSpace(token)){base.HandleUnauthorizedRequest(filterContext);}//獲取登錄時間var loginTime = Convert.ToDateTime(filterContext.HttpContext.Application[token]);//將登錄時間與當(dāng)前的時間進行對比來判斷是否為登錄狀態(tài)if (loginTime > DateTime.UtcNow){//驗證通過}else{base.HandleUnauthorizedRequest(filterContext);}}} }然后打開index.cshtml添加登錄窗體與測試登錄后=訪問的鏈接
<div class="row"><div class="col-md-12">@using (Html.BeginForm("Login", "Home")){<input type="text" name="account" class="form-control" />@Html.Password("password", null, new { @class = "form-control" })<button>登錄</button>}</div> </div> <a href="@Url.Action("test")" class="btn btn-block btn-success">登錄后才能進入</a>為了訪問此登錄后的鏈接,打開HomeController,添加test的action
??????? [AuthorizePlus]public ActionResult Test(){return Content("登入成功");}使用AuthorizePlus注解需要添加命名空間
using System.Web.Mvc;然后運行項目,如果沒有登錄直接點擊測試鏈接后
?
只有輸入正確的用戶名mvc和密碼123456之后,再點擊測試鏈接
?
示例代碼下載
https://download.csdn.net/download/BADAO_LIUMANG_QIZHI/12584817
總結(jié)
以上是生活随笔為你收集整理的ASP.NET的MVC中使用Cookie做身份验证(附代码下载)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET的MVC中使用Sessio
- 下一篇: ASP.NET中新建Web网站并部署到I