MVC中Forms身份驗(yàn)證身份驗(yàn)證流程

驗(yàn)證流程

一、用戶登錄
  1、驗(yàn)證表單:ModelState.IsValid
  2、驗(yàn)證用戶名和密碼:通過(guò)查詢數(shù)據(jù)庫(kù)驗(yàn)證
  3、如果用戶名和密碼正確,則在客戶端保存Cookie以保存用戶登錄狀態(tài):SetAuthCookie
    1):從數(shù)據(jù)庫(kù)中查出用戶名和一些必要的信息,并把額外信息保存到UserData中
    2):把用戶名和UserData保存到 FormsAuthenticationTicket 票據(jù)中
    3):對(duì)票據(jù)進(jìn)行加密 Encrypt
    4):將加密后的票據(jù)保存到Cookie發(fā)送到客戶端
  4、跳轉(zhuǎn)到登錄前的頁(yè)面
5、如果登錄失敗,返回當(dāng)前視圖
二、驗(yàn)證登錄
  1、在Global中注冊(cè)PostAuthenticateRequest事件函數(shù),用于解析客戶端發(fā)過(guò)來(lái)的Cookie數(shù)據(jù)
    1):通過(guò) HttpContext.Current.User.Identity 判斷用戶是否登錄(FormsIdentity,IsAuthenticated,AuthenticationType)
    2):從HttpContext 的Request的Cookie中解析出Value,解密得到 FormsAuthenticationTicket 得到UserData
  2、角色驗(yàn)證
    在Action加入 Authorize特性,可以進(jìn)行角色驗(yàn)證
    在 HttpContext.Current.User 的 IsInRole 方法進(jìn)行角色認(rèn)證(需要重寫(xiě))

一、用戶登錄

1、設(shè)置web.config

設(shè)置重定向登錄頁(yè)面
<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、登陸的驗(yàn)證中控制器

控制器中加“[Authorize]”修飾的方法拒絕匿名。
 public class UserInfoController : Controller //控制器
 {
    //身份驗(yàn)證過(guò)濾器
        [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)
                {
                    //存入票據(jù)(用戶登錄的時(shí)候去存信息,如果有信息直接去登錄)
                    var dtoModel = new Users
                    {
                        id = model.id,
                        AdminPwd = model.AdminPwd,
                        AdminAccount=model.AdminAccount
                    };
                    //調(diào)用
                    SetAuthCookie(dtoModel);
                    //獲取登錄地址
                    var returnUrl = Request["ReturnUrl"];
                    //判斷登錄地址是不是空值
                    if (!string.IsNullOrWhiteSpace(returnUrl))
                    {                      
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        //return RedirectiToAction
                        return Redirect("/Home/index");
                    }

                }
                else
                {
                    ModelState.AddModelError("", "賬號(hào)密碼不對(duì)");
                    return View(login);
                }
            }
            else
            {
                ModelState.AddModelError("", "輸入的信息有誤");
                return View(login);

            }

對(duì)登錄賬號(hào)進(jìn)行cookie
        /// <summary>
        /// 對(duì)登錄賬號(hào)進(jìn)行cookie
        /// </summary>
        /// <param name="model"></param>
        public void SetAuthCookie(Users loginModel) {
            //1、將對(duì)象轉(zhuǎn)換成json
            var userdata = loginModel.ToJson();
            //2、創(chuàng)建票據(jù)FormsAuthenticationTicket
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,"loginUser",DateTime.Now,DateTime.Now.AddDays(1), false, userdata);
            //對(duì)票據(jù)進(jìn)行加密 
            var tickeEncrypt = FormsAuthentication.Encrypt(ticket);
            //創(chuàng)建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>
        /// 賬號(hào)
        /// </summary>
        [DisplayName("賬號(hào)")]
        [Required(ErrorMessage = "賬號(hào)不能為空")]   
        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設(shè)置

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

                }
            }
        }

6、退出登錄

控制器中
        /// <summary>
        /// 退出登錄
        /// </summary>
        public ActionResult loginout()
        {
            //刪除票據(jù)
            FormsAuthentication.SignOut();
            //清除cookie
            Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            return RedirectToAction("Index", "Home");
 
        }
View跳轉(zhuǎn)鏈接
@Html.ActionLink("安全退出","loginout","Users")
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評(píng)論 19 139
  • 今天webryan給team做了一個(gè)關(guān)于HTTP cookie的分享,從各個(gè)方面給大家介紹一下大家耳熟能詳?shù)腃oo...
    秒贊不是偶然閱讀 8,819評(píng)論 0 20
  • HTTP cookie(也稱為web cookie,網(wǎng)絡(luò)cookie,瀏覽器cookie或者簡(jiǎn)稱cookie)是網(wǎng)...
    留七七閱讀 18,382評(píng)論 2 71
  • 明天一切就該收拾好了,同一時(shí)間,就要度過(guò)這里的最后一個(gè)夜晚! 法租界,真的不敢相信自己住在這里差不多半年之久。然后...
    夏威一一閱讀 111評(píng)論 0 0
  • [作者]周潔華 [派別]文魁派 [導(dǎo)師]袁文魁、王玉印 [分舵]第三分舵 思維圖騰 [舵主]林麗莉 一開(kāi)始聽(tīng)到這個(gè)...
    周潔華zjh閱讀 386評(píng)論 1 0

友情鏈接更多精彩內(nèi)容