asp.net Forms authentication process in MVC

Time:2021-4-13

Verification process

1、 User login

1. Validation form: ModelState.IsValid
2. Verify user name and password: verify by querying the database
3. If the user name and password are correct, save the 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 the UserData
2): save the user name and UserData to the forms authentication ticket
3): encrypt the bill
4): save the encrypted bill to the cookie and send it to the client
4. Jump to the page before login
5. If login fails, return to the current view

2、 Verify login

1. Register the postauthenticaterequest event function in global to parse the cookie data sent by the client
1): passed HttpContext.Current.User . identity determines whether the user logs in (forms identity, isauthenticated, authenticationtype)
2): parse value from the cookie of httpcontext’s request, decrypt to get formsauthenticationticket, and get UserData
2. Role validation
1): add the authorize feature in the action to verify the role
2): in HttpContext.Current.User The IsInRole method for role authentication (needs to be overridden)

1、 User login

1. Settings web.config

Set up the redirection 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 it out


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

2. Login controller in verification

The method decorated with “[authorize]” in the controller refuses to be anonymous.

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

    }
    else
    {
     ModelState.AddModelError ("," wrong account password ");
     return View(login);
    }
   }
   else
   {
    ModelState.AddModelError ("," the input information is incorrect ");
    return View(login);

   }

Cookie login account

/// <summary>
  ///Cookie login account
  /// </summary>
  /// <param name="model"></param>
  public void SetAuthCookie(Users loginModel) {
   //1. Convert object to JSON
   var userdata = loginModel.ToJson();
   //2. Create ticket formsauthenticationticket
   FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,"loginUser",DateTime.Now,DateTime.Now.AddDays(1), false, userdata);
   //Encryption of bills 
   var tickeEncrypt = FormsAuthentication.Encrypt(ticket);
   //Create cookies, define
   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);
   //First remove the cookie, then add the cookie
   Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
   Response.Cookies.Add(cookie);
  }

3. Add model files to models

public class loginModels
 {
  /// <summary>
  ///Account number
  /// </summary>
  [displayName ("account")]
  [required (ErrorMessage = account cannot be empty)] 
  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:

Copy codeThe code is as follows:
@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. Get HTTP request through sender
   //Httpapplication app = new httpapplication(); // instantiation
   HttpApplication app = sender as HttpApplication;
   //2. Get the HTTP context
   HttpContext context = app.Context;
   //3. According to formsause, get the cookie
   var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
   if (cookie != null)
   {
    //Gets the value of the cookie
    var ticket = FormsAuthentication.Decrypt(cookie.Value);
    if (!string.IsNullOrWhiteSpace(ticket.UserData))
    {
     //Turn a string category into an entity model
     var model = ticket.UserData.ToObject<AdmininfoViewModel>();
     //var acount =  model.AdminAccount ; // get 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
  /// </summary>
  public ActionResult loginout()
  {
   //Delete bill
   FormsAuthentication.SignOut();
   //Clear cookies
   Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddDays(-1);
   Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
   return RedirectToAction("Index", "Home");
 
  }

View jump link

@ Html.ActionLink (security exit, loginout, users)

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.

Recommended Today

Review of SQL Sever basic command

catalogue preface Installation of virtual machine Commands and operations Basic command syntax Case sensitive SQL keyword and function name Column and Index Names alias Too long to see? Space Database connection Connection of SSMS Connection of command line Database operation establish delete constraint integrity constraint Common constraints NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY DEFAULT […]