這里我們采用asp.net mvc 自帶的AuthorizeAttribute過濾器驗證用戶的身份,也可以使用自定義過濾器,步驟都是一樣。
第一步:創建asp.net mvc項目, 在項目的App_Start文件夾下面有一個FilterConfig.cs,在這個文件中可以注冊全局的過濾器。我們在文件中添加AuthorizeAttribute過濾器如下:
1
2
3
4
5
6
7
8
9
|
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add( new HandleErrorAttribute()); //將內置的權限過濾器添加到全局過濾中 filters.Add( new System.Web.Mvc.AuthorizeAttribute()); } } |
第二步:在web.config配置文件中修改網站的身份認證為mode="Forms"
1
2
3
4
5
6
7
8
|
< system.web > <!--Cockie名稱,當用未登入時跳轉的url--> < authentication mode = "Forms" > < forms name = "xCookie" loginUrl = "~/Login/Index" protection = "All" timeout = "60" cookieless = "UseCookies" ></ forms > </ authentication > < compilation debug = "true" targetFramework = "4.5" /> < httpRuntime targetFramework = "4.5" /> </ system.web > |
提示:配置name值作為最終生成的cookie的名稱,loginUrl指定當用戶未登入是跳轉的頁面,這里挑戰到登入頁面
第三步:添加用戶登入相關的控制器和視圖
創建LoginController控制器:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
public class LoginController : Controller { [HttpGet] [AllowAnonymous] public ActionResult Index() { return View(); } [HttpPost] [AllowAnonymous] public ActionResult Login(User user) { if (!user.Username.Trim().Equals( "liuxin" ) || !user.Password.Trim().Equals( "abc" )) { ModelState.AddModelError( "" , "用戶名或密碼錯誤" ); return View( "index" , user); } //if (!user.Username.Trim().Equals("liuxin")) { // ModelState.AddModelError("Username", "用戶名錯誤"); // return View("index", user); //} //if (!user.Password.Trim().Equals("abc")) { // ModelState.AddModelError("Password", "密碼錯誤"); // return View("index", user); //} user.Id = Guid.NewGuid().ToString( "D" ); //為了測試手動設置一個用戶id FormsAuthHelp.AddFormsAuthCookie(user.Id, user, 60); //設置ticket票據的名稱為用戶的id,設置有效時間為60分鐘 return Redirect( "~" ); } [HttpGet] public ActionResult Logout() { FormsAuthHelp.RemoveFormsAuthCookie(); return Redirect( "~/Login/Index" ); } } |
特別注意:Index和Login這兩個方法得使用“[AllowAnonymous]”指明這兩個方法可以匿名訪問,否則由于過濾器不允許匿名訪問,導致登入頁面和用戶提交都無法進行。顯然這不是我們希望看到的。
提示:為了測試方便這邊的用戶的數據是寫死的,用戶的id也是臨時生成了一個
1
2
3
4
5
6
|
public class User { public string Id { get ; set ; } public string Username { get ; set ; } public string Password { get ; set ; } } |
創建登入視圖:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@{ Layout = null ; ViewBag.Title = "Index" ; } <h3>您尚未登入,請登入</h3> @ using (Html.BeginForm( "Login" , "Login" , FormMethod.Post)) { @Html.Label( "Username" , "用戶名:" )@Html.TextBox( "Username" , null , new { id = "Username" , placeholder = "請輸入用戶名" }) @Html.ValidationMessage( "Username" )<br/> @Html.Label( "Password" , "密 碼:" )@Html.TextBox( "Password" , null , new { id = "Password" , placeholder = "請輸入密碼" }) @Html.ValidationMessage( "Password" )<br/> <input type= "submit" value= "登入" /> <input type= "reset" value= "重置" /> @Html.ValidationSummary( true ) } |
提示:當檢測到用戶未登入,則跳轉到web.config中配置的url頁面,當用戶填寫密碼并提交時,用戶輸入的數據會提交到LoginController控制器下的Login方法,驗證用戶的輸入,認證失敗重新返回到登入界面,當認證成功,將會執行
<<***FormsAuthHelp.AddFormsAuthCookie(user.Id, user, 60);//設置ticket票據的名稱為用戶的id,設置有效時間為60分鐘***>>,這條語句的作用是生成一個ticket票據,并封裝到cookie中,asp.net mvc正式通過檢測這個cookie認證用戶是否登入的,具體代碼如下
第四步:將用戶信息生成ticket封裝到cookie中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
public class FormsAuthHelp { /// <summary> /// 將當前登入用戶的信息生成ticket添加到到cookie中(用于登入) /// </summary> /// <param name="loginName">Forms身份驗證票相關聯的用戶名(一般是當前用戶的id,作為ticket的名稱使用)</param> /// <param name="userData">用戶信息</param> /// <param name="expireMin">有效期</param> public static void AddFormsAuthCookie( string loginName, object userData, int expireMin) { //將當前登入的用戶信息序列化 var data = JsonConvert.SerializeObject(userData); //創建一個FormsAuthenticationTicket,它包含登錄名以及額外的用戶數據。 var ticket = new FormsAuthenticationTicket(1, loginName, DateTime.Now, DateTime.Now.AddDays(1), true , data); //加密Ticket,變成一個加密的字符串。 var cookieValue = FormsAuthentication.Encrypt(ticket); //根據加密結果創建登錄Cookie //FormsAuthentication.FormsCookieName是配置文件中指定的cookie名稱,默認是".ASPXAUTH" var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue) { HttpOnly = true , Secure = FormsAuthentication.RequireSSL, Domain = FormsAuthentication.CookieDomain, Path = FormsAuthentication.FormsCookiePath }; //設置有效時間 if (expireMin > 0) cookie.Expires = DateTime.Now.AddMinutes(expireMin); var context = HttpContext.Current; if (context == null ) throw new InvalidOperationException(); //寫登錄Cookie context.Response.Cookies.Remove(cookie.Name); context.Response.Cookies.Add(cookie); } /// <summary> /// 刪除用戶ticket票據 /// </summary> public static void RemoveFormsAuthCookie() { FormsAuthentication.SignOut(); } } |
第五步:測試執行
1. 啟動網站輸入相應的網址:如下圖
2. 此時用戶尚未登入將會跳轉到登入界面:如下圖
3.輸入錯誤的密碼會重新跳轉到登入界面并提示出錯
4. 輸入正確的用戶名密碼
5.點擊用戶退出會刪除掉cookie所以又會跳轉到登入界面。
源碼下載地址:鏈接: https://pan.baidu.com/s/1cm722q 密碼: ut53
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/enfp/archive/2017/10/24/7723973.html