溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Asp.net mvc驗證用戶登錄之Forms實現(xiàn)的示例分析

發(fā)布時間:2021-07-13 11:58:44 來源:億速云 閱讀:181 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹了Asp.net mvc驗證用戶登錄之Forms實現(xiàn)的示例分析,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

這里我們采用asp.net mvc 自帶的AuthorizeAttribute過濾器驗證用戶的身份,也可以使用自定義過濾器,步驟都是一樣。

第一步:創(chuàng)建asp.net mvc項目, 在項目的App_Start文件夾下面有一個FilterConfig.cs,在這個文件中可以注冊全局的過濾器。我們在文件中添加AuthorizeAttribute過濾器如下:

public class FilterConfig
 {
  public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  {
   filters.Add(new HandleErrorAttribute());
   //將內(nèi)置的權(quán)限過濾器添加到全局過濾中
   filters.Add(new System.Web.Mvc.AuthorizeAttribute());
  }
 }

第二步:在web.config配置文件中修改網(wǎng)站的身份認證為mode="Forms"

<system.web>
 <!--Cockie名稱,當(dāng)用未登入時跳轉(zhuǎn)的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指定當(dāng)用戶未登入是跳轉(zhuǎn)的頁面,這里挑戰(zhàn)到登入頁面

第三步:添加用戶登入相關(guān)的控制器和視圖

創(chuàng)建LoginController控制器:

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");//為了測試手動設(shè)置一個用戶id
   FormsAuthHelp.AddFormsAuthCookie(user.Id, user, 60);//設(shè)置ticket票據(jù)的名稱為用戶的id,設(shè)置有效時間為60分鐘
   return Redirect("~");
  }
  [HttpGet]
  public ActionResult Logout() {
   FormsAuthHelp.RemoveFormsAuthCookie();
   return Redirect("~/Login/Index");
  }
 }

特別注意:Index和Login這兩個方法得使用“[AllowAnonymous]”指明這兩個方法可以匿名訪問,否則由于過濾器不允許匿名訪問,導(dǎo)致登入頁面和用戶提交都無法進行。顯然這不是我們希望看到的。

提示:為了測試方便這邊的用戶的數(shù)據(jù)是寫死的,用戶的id也是臨時生成了一個

public class User
 {
  public string Id { get; set; }
  public string Username { get; set; }
  public string Password { get; set; }
 }

創(chuàng)建登入視圖:

@{
 Layout = null;
 ViewBag.Title = "Index";
}
<h4>您尚未登入,請登入</h4>
@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)
}

提示:當(dāng)檢測到用戶未登入,則跳轉(zhuǎn)到web.config中配置的url頁面,當(dāng)用戶填寫密碼并提交時,用戶輸入的數(shù)據(jù)會提交到LoginController控制器下的Login方法,驗證用戶的輸入,認證失敗重新返回到登入界面,當(dāng)認證成功,將會執(zhí)行

<<***FormsAuthHelp.AddFormsAuthCookie(user.Id, user, 60);//設(shè)置ticket票據(jù)的名稱為用戶的id,設(shè)置有效時間為60分鐘***>>,這條語句的作用是生成一個ticket票據(jù),并封裝到cookie中,asp.net mvc正式通過檢測這個cookie認證用戶是否登入的,具體代碼如下

第四步:將用戶信息生成ticket封裝到cookie中

public class FormsAuthHelp
 {
  /// <summary>
  /// 將當(dāng)前登入用戶的信息生成ticket添加到到cookie中(用于登入)
  /// </summary>
  /// <param name="loginName">Forms身份驗證票相關(guān)聯(lián)的用戶名(一般是當(dāng)前用戶的id,作為ticket的名稱使用)</param>
  /// <param name="userData">用戶信息</param>
  /// <param name="expireMin">有效期</param>
  public static void AddFormsAuthCookie(string loginName, object userData, int expireMin)
  {
   //將當(dāng)前登入的用戶信息序列化
   var data = JsonConvert.SerializeObject(userData);

   //創(chuàng)建一個FormsAuthenticationTicket,它包含登錄名以及額外的用戶數(shù)據(jù)。
   var ticket = new FormsAuthenticationTicket(1,
    loginName, DateTime.Now, DateTime.Now.AddDays(1), true, data);

   //加密Ticket,變成一個加密的字符串。
   var cookieValue = FormsAuthentication.Encrypt(ticket);

   //根據(jù)加密結(jié)果創(chuàng)建登錄Cookie
   //FormsAuthentication.FormsCookieName是配置文件中指定的cookie名稱,默認是".ASPXAUTH"
   var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue)
   {
    HttpOnly = true,
    Secure = FormsAuthentication.RequireSSL,
    Domain = FormsAuthentication.CookieDomain,
    Path = FormsAuthentication.FormsCookiePath
   };
   //設(shè)置有效時間
   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票據(jù)
  /// </summary>
  public static void RemoveFormsAuthCookie() {
   FormsAuthentication.SignOut();
  }
 }

第五步:測試執(zhí)行

1. 啟動網(wǎng)站輸入相應(yīng)的網(wǎng)址:如下圖

Asp.net mvc驗證用戶登錄之Forms實現(xiàn)的示例分析

2. 此時用戶尚未登入將會跳轉(zhuǎn)到登入界面:如下圖

Asp.net mvc驗證用戶登錄之Forms實現(xiàn)的示例分析

3.輸入錯誤的密碼會重新跳轉(zhuǎn)到登入界面并提示出錯

Asp.net mvc驗證用戶登錄之Forms實現(xiàn)的示例分析

4. 輸入正確的用戶名密碼

Asp.net mvc驗證用戶登錄之Forms實現(xiàn)的示例分析

感謝你能夠認真閱讀完這篇文章,希望小編分享的“Asp.net mvc驗證用戶登錄之Forms實現(xiàn)的示例分析”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI