首頁  >  文章  >  後端開發  >  asp.net mvc中實作Forms驗證驗證流程的實例

asp.net mvc中實作Forms驗證驗證流程的實例

黄舟
黄舟原創
2018-05-14 13:48:534093瀏覽

這篇文章主要介紹了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驗證驗證流程的實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn