asp. net Forms Authentication Process in mvc

  • 2021-10-13 07:09:02
  • OfStack

Verification process

1. User login

1. Verification form: ModelState. IsValid
2. Verify username and password: Verify by querying the database
3. If the user name and password are correct, save Cookie on the client to save the user login status: SetAuthCookie
1): Find out the user name and some necessary information from the database, and save the additional information to UserData
2): Save user name and UserData to FormsAuthenticationTicket ticket
3): Encrypt the ticket Encrypt
4): Save the encrypted ticket to Cookie and send it to the client
4. Jump to the page before logging in
5. If login fails, return to the current view

2. Verify login

1. Register PostAuthenticateRequest event function in Global to parse Cookie data sent by client
1): Judge whether the user logs in (FormsIdentity, IsAuthenticated, AuthenticationType) by HttpContext. Current. User. Identity
2) Parsing Value from Request of HttpContext, decrypting FormsAuthenticationTicket to obtain UserData
2. Role verification
1): Add Authorize feature to Action, and role verification can be carried out
2): Role authentication in IsInRole method of HttpContext. Current. User (need to be overridden)

1. User login

1. Set web. config

Set up the redirect login page


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

Comment out


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

2. Login verification controller

The method decorated with "[Authorize]" in the controller refuses anonymity.


 public class UserInfoController : Controller // Controller 
 {
 // Authentication filter 
  [Authorize]
  public ActionResult Index()
  {
   return View();
  }
 }

Login in controller


   /// <summary>
  ///  User login 
  /// </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)
    {
     // Save the bill (when the user logs in, save the information, and log in directly if there is information) 
     var dtoModel = new Users
     {
      id = model.id,
      AdminPwd = model.AdminPwd,
      AdminAccount=model.AdminAccount
     };
     // Call 
     SetAuthCookie(dtoModel);
     // Get the login address 
     var returnUrl = Request["ReturnUrl"];
     // Determining whether the login address is null or not 
     if (!string.IsNullOrWhiteSpace(returnUrl))
     {      
      return Redirect(returnUrl);
     }
     else
     {
      //return RedirectiToAction
      return Redirect("/Home/index");
     }

    }
    else
    {
     ModelState.AddModelError("", " Incorrect account password ");
     return View(login);
    }
   }
   else
   {
    ModelState.AddModelError("", " The information entered is incorrect ");
    return View(login);

   }

Perform cookie on the login account


  /// <summary>
  ///  Proceed to the login account cookie
  /// </summary>
  /// <param name="model"></param>
  public void SetAuthCookie(Users loginModel) {
   //1 Converts an object to a json
   var userdata = loginModel.ToJson();
   //2 Create a ticket FormsAuthenticationTicket
   FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,"loginUser",DateTime.Now,DateTime.Now.AddDays(1), false, userdata);
   // Encrypt the ticket  
   var tickeEncrypt = FormsAuthentication.Encrypt(ticket);
   // Create Cookie , definition 
   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);
   // Remove first cookie In the addition of cookie
   Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
   Response.Cookies.Add(cookie);
  } 

3. Adding model files to Models


 public class loginModels
 {
  /// <summary>
  ///  Account number 
  /// </summary>
  [DisplayName(" Account number ")]
  [Required(ErrorMessage = " Account number cannot be blank ")] 
  public string AdminAccount { get; set; }
  /// <summary>
  ///  Password 
  /// </summary>
  [DisplayName(" Password ")]
  [Required(ErrorMessage = " Password cannot be empty ")]
  public string AdminPwd { get; set; }
 }

4. Login code in Views:


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

5. Global Settings


protected void Application_AuthenticateRequest(object sender, EventArgs e)
  {
   //1 , through sender Get http Request 
   // HttpApplication app = new HttpApplication();// Instantiation 
   HttpApplication app = sender as HttpApplication;
   //2 , get it http Context 
   HttpContext context = app.Context;
   //3 , according to FormsAuthe, To get cookie
   var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
   if (cookie != null)
   {
    // Get cookie Value of 
    var ticket = FormsAuthentication.Decrypt(cookie.Value);
    if (!string.IsNullOrWhiteSpace(ticket.UserData))
    {
     // Put 1 String classes become solid models 
     var model = ticket.UserData.ToObject<AdmininfoViewModel>();
     //var acount = model.AdminAccount; // Acquisition account number 
     context.User = new MyFormsPrincipal<AdmininfoViewModel>(ticket, model);
     //MyFormsPrincipal.Identity = new FormsIdentity(ticket);
     // MyFormsPrincipal.userdata;

    }
   }
  }

6. Log out

In the controller


  /// <summary>
  ///  Log out of the login 
  /// </summary>
  public ActionResult loginout()
  {
   // Delete a bill 
   FormsAuthentication.SignOut();
   // Clear cookie
   Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddDays(-1);
   Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
   return RedirectToAction("Index", "Home");
 
  }

View Jump Link


@Html.ActionLink(" Safe exit ","loginout","Users")

Related articles: