SoFunction
Updated on 2025-03-10

Forms authentication authentication process in mvc

Verification process

1. User login

1. Verification form:
2. Verify username and password: Verify by querying the database
3. If the username and password are correct, save the cookie on the client to save the user's 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 the username and UserData into the FormsAuthenticationTicket ticket
3): Encrypt the bills Encrypt
4): Save the encrypted ticket 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): Determine whether the user is logged in (FormsIdentity, IsAuthenticated, AuthenticationType)
2): parse out the value from the cookie of the Request of HttpContext, decrypt it to get the FormsAuthenticationTicket and get UserData
2. Role verification
1): Add Authorize to Action, and role verification can be performed
2): Perform role authentication in the IsInRole method (rewrite required)

1. User login

1. Settings

Set up redirect login page

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

Comment out

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

2. Login verification controller

The method of adding "[Authorize]" to the controller refuses to be anonymous.

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

Log in to the controller

   /// &lt;summary&gt;
  /// User login  /// &lt;/summary&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public ActionResult login()
  {
   return View();
  }  
  [HttpPost]
  public ActionResult login(loginModels login) {
   if ()
   {
    var model = (a =&gt;  ==  &amp;&amp;  == );
    if (model != null)
    {
     //Save the bill (use the information when the user logs in, and log in directly if there is any information)     var dtoModel = new Users
     {
      id = ,
      AdminPwd = ,
      AdminAccount=
     };
     //Call     SetAuthCookie(dtoModel);
     //Get login address     var returnUrl = Request["ReturnUrl"];
     //Discern whether the login address is empty     if (!(returnUrl))
     {      
      return Redirect(returnUrl);
     }
     else
     {
      //return RedirectiToAction
      return Redirect("/Home/index");
     }

    }
    else
    {
     ("", "The account password is incorrect");
     return View(login);
    }
   }
   else
   {
    ("", "The input information is incorrect");
    return View(login);

   }

Cookies on login account

  /// &lt;summary&gt;
  /// Cookies the login account  /// &lt;/summary&gt;
  /// &lt;param name="model"&gt;&lt;/param&gt;
  public void SetAuthCookie(Users loginModel) {
   //1. Convert object to json   var userdata = ();
   //2. Create a ticket FormsAuthenticationTicket   FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,"loginUser",,(1), false, userdata);
   //Encrypt the bill   var tickeEncrypt = (ticket);
   //Create a cookie, define it   HttpCookie cookie = new HttpCookie(, tickeEncrypt);
    = true;
    = ;
    = ;
    = ;
    = ();
   //Remove cookies first and add cookies   ();
   (cookie);
  } 

3. Add model files in Models

 public class loginModels
 {
  /// &lt;summary&gt;
  /// account  /// &lt;/summary&gt;
  [DisplayName("account")]
  [Required(ErrorMessage = "The account cannot be empty")] 
  public string AdminAccount { get; set; }
  /// &lt;summary&gt;
  /// password  /// &lt;/summary&gt;
  [DisplayName("password")]
  [Required(ErrorMessage = "Password cannot be empty")]
  public string AdminPwd { get; set; }
 }

4. Login code in Views:

Copy the codeThe code is as follows:

@using (("Login", "Account", new { ReturnUrl = }, , 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 = ;
   //3. Obtain cookies according to FormsAuthe   var cookie = [];
   if (cookie != null)
   {
    //Get the value of the cookie    var ticket = ();
    if (!())
    {
     //Turn a string category into a solid model     var model = &lt;AdmininfoViewModel&gt;();
     //var account = ; //Get account      = new MyFormsPrincipal&lt;AdmininfoViewModel&gt;(ticket, model);
     // = new FormsIdentity(ticket);
     // ;

    }
   }
  }

6. Log out

In the controller

  /// &lt;summary&gt;
  /// Log out  /// &lt;/summary&gt;
  public ActionResult loginout()
  {
   //Delete the bill   ();
   //Clear cookies   [].Expires = (-1);
   ();
   return RedirectToAction("Index", "Home");
 
  }

View jump link

@("Safe Exit","loginout","Users")

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.