国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

asp.net mvc中Forms身份驗證身份驗證流程

2024-07-10 12:54:40
字體:
來源:轉載
供稿:網友

MVC程序開發過程中,我們經常會遇到控制器或操作方法,而我們只有在用戶登錄后才能訪問,下面讓錯新技術頻道小編分享asp.net mvc中Forms身份驗證身份驗證流程,希望對大家有幫助。

驗證流程

一、用戶登錄

1、驗證表單:ModelState.IsValid
2、驗證用戶名和密碼:通過查詢數據庫驗證
3、如果用戶名和密碼正確,則在客戶端保存Cookie以保存用戶登錄狀態:SetAuthCookie
??? 1):從數據庫中查出用戶名和一些必要的信息,并把額外信息保存到UserData中
 2):把用戶名和UserData保存到 FormsAuthenticationTicket 票據中
 3):對票據進行加密 Encrypt
 4):將加密后的票據保存到Cookie發送到客戶端
4、跳轉到登錄前的頁面
5、如果登錄失敗,返回當前視圖

二、驗證登錄

1、在Global中注冊PostAuthenticateRequest事件函數,用于解析客戶端發過來的Cookie數據
 1):通過 HttpContext.Current.User.Identity 判斷用戶是否登錄(FormsIdentity,IsAuthenticated,AuthenticationType)
 2):從HttpContext 的Request的Cookie中解析出Value,解密得到 FormsAuthenticationTicket 得到UserData
2、角色驗證
 1):在Action加入 Authorize特性,可以進行角色驗證
 2):在 HttpContext.Current.User 的 IsInRole 方法進行角色認證(需要重寫)

一、用戶登錄

1、設置web.config

設置重定向登錄頁面

<system.web><authentication mode="Forms">  <forms name="loginName" loginUrl="/UserInfo/login" cookieless="UseCookies" path="/" protection="All" timeout="30"></forms></authentication></system.web>

注釋掉

<modules>  <!--<remove name="FormsAuthentication" />--></modules>

2、登陸的驗證中控制器

控制器中加“[Authorize]”修飾的方法拒絕匿名。

 public class UserInfoController : Controller //控制器 { //身份驗證過濾器  [Authorize]  public ActionResult Index()  {   return View();  } }

控制器中登錄

   /// <summary>  /// 用戶登錄  /// </summary>  /// <returns></returns>  public ActionResult login()  {   return View();  }    [HttpPost]  public ActionResult login(loginModels login) {   if (ModelState.IsValid)   {    var model = db.Admininfo.FirstOrDefault(a => a.AdminAccount == login.AdminAccount && a.AdminPwd == login.AdminPwd);    if (model != null)    {     //存入票據(用戶登錄的時候去存信息,如果有信息直接去登錄)     var dtoModel = new Users     {      id = model.id,      AdminPwd = model.AdminPwd,      AdminAccount=model.AdminAccount     };     //調用     SetAuthCookie(dtoModel);     //獲取登錄地址     var returnUrl = Request["ReturnUrl"];     //判斷登錄地址是不是空值     if (!string.IsNullOrWhiteSpace(returnUrl))     {            return Redirect(returnUrl);     }     else     {      //return RedirectiToAction      return Redirect("/Home/index");     }    }    else    {     ModelState.AddModelError("", "賬號密碼不對");     return View(login);    }   }   else   {    ModelState.AddModelError("", "輸入的信息有誤");    return View(login);   }

對登錄賬號進行cookie

  /// <summary>  /// 對登錄賬號進行cookie  /// </summary>  /// <param name="model"></param>  public void SetAuthCookie(Users loginModel) {   //1、將對象轉換成json   var userdata = loginModel.ToJson();   //2、創建票據FormsAuthenticationTicket   FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,"loginUser",DateTime.Now,DateTime.Now.AddDays(1), false, userdata);   //對票據進行加密    var tickeEncrypt = FormsAuthentication.Encrypt(ticket);   //創建Cookie,定義   HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, tickeEncrypt);   cookie.HttpOnly = true;   cookie.Secure = FormsAuthentication.RequireSSL;   cookie.Domain = FormsAuthentication.CookieDomain;   cookie.Path = FormsAuthentication.FormsCookiePath;   cookie.Expires = DateTime.Now.Add(FormsAuthentication.Timeout);   //先移除cookie,在添加cookie   Response.Cookies.Remove(FormsAuthentication.FormsCookieName);   Response.Cookies.Add(cookie);  } 

3、Models中添加模型文件

 public class loginModels {  /// <summary>  /// 賬號  /// </summary>  [DisplayName("賬號")]  [Required(ErrorMessage = "賬號不能為空")]   public string AdminAccount { get; set; }  /// <summary>  /// 密碼  /// </summary>  [DisplayName("密碼")]  [Required(ErrorMessage = "密碼不能為空")]  public string AdminPwd { get; set; } }

4、Views中 Login 代碼:

?

復制代碼 代碼如下:

@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))

?

?

?

5、Global設置

protected void Application_AuthenticateRequest(object sender, EventArgs e)  {   //1、通過sender獲取http請求   // HttpApplication app = new HttpApplication();//實例化   HttpApplication app = sender as HttpApplication;   //2、拿到http上下文   HttpContext context = app.Context;   //3、根據FormsAuthe,來獲取cookie   var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];   if (cookie != null)   {    //獲取cookie的值    var ticket = FormsAuthentication.Decrypt(cookie.Value);    if (!string.IsNullOrWhiteSpace(ticket.UserData))    {     //把一個字符串類別變成實體模型     var model = ticket.UserData.ToObject<AdmininfoViewModel>();     //var acount = model.AdminAccount; //獲取賬號     context.User = new MyFormsPrincipal<AdmininfoViewModel>(ticket, model);     //MyFormsPrincipal.Identity = new FormsIdentity(ticket);     // MyFormsPrincipal.userdata;    }   }  }

6、退出登錄

控制器中

  /// <summary>  /// 退出登錄  /// </summary>  public ActionResult loginout()  {   //刪除票據   FormsAuthentication.SignOut();   //清除cookie   Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddDays(-1);   Response.Cookies.Remove(FormsAuthentication.FormsCookieName);   return RedirectToAction("Index", "Home");   }

View跳轉鏈接

@Html.ActionLink("安全退出","loginout","Users")

上述是asp.net mvc中Forms身份驗證身份驗證流程的介紹,錯新技術頻道至今也為大家分享了很多專業知識,目前來看還算比較符合程序員們的口味,希望能幫到大家。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 庄浪县| 青阳县| 台南县| 沙河市| 永定县| 娄烦县| 宝丰县| 瑞金市| 慈溪市| 陵川县| 炎陵县| 湟中县| 石屏县| 交城县| 化隆| 宁夏| 曲沃县| 嘉定区| 额敏县| 屯昌县| 宝应县| 黄平县| 芮城县| 繁峙县| 朝阳县| 宁海县| 苍山县| 株洲县| 连江县| 朝阳市| 滦平县| 法库县| 邛崃市| 全州县| 凤城市| 鹿邑县| 印江| 承德县| 商城县| 隆德县| 北碚区|