Forms authentication process in asp.net mvc, mvcforms

Source: Internet
Author: User

Forms authentication process in asp.net mvc, mvcforms

Verification process

1. User Logon

1. Verification Form: ModelState. IsValid
2. Verify the 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's logon status: SetAuthCookie
1): Find the username and necessary information from the database, and save the additional information to UserData.
2): Save the user name and UserData to the FormsAuthenticationTicket ticket.
3): Encrypt the ticket with Encrypt
4): Save the encrypted ticket to the Cookie and send it to the client.
4. Jump to the page before Logon
5. If logon fails, return to the current view.

Ii. Verify Logon

1. register the PostAuthenticateRequest event function in Global to parse the Cookie data sent from the client.
1): Use HttpContext. Current. User. Identity to determine whether a User is logged on (FormsIdentity, IsAuthenticated, AuthenticationType)
2): parse the Value from the Cookie of HttpContext Request and decrypt it to get FormsAuthenticationTicket to get UserData.
2. Role Verification
1): Add the Authorize feature to the Action for role verification.
2): Perform role authentication in the IsInRole method of HttpContext. Current. User (rewrite required)

1. User Logon

1. Set web. config

Set redirect logon 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. Controller in login verification

The "[Authorize]" modifier in the Controller rejects anonymity.

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

Logon in Controller

/// <Summary> // User Logon // </summary> /// <returns> </returns> public ActionResult login () {return View ();} [HttpPost] public ActionResult login (loginModels login) {if (ModelState. isValid) {var model = db. admininfo. firstOrDefault (a =>. adminAccount = login. adminAccount &. adminPwd = login. adminPwd); if (model! = Null) {// deposit the ticket (the user saves the information when logging on, and directly logs on if there is information) var dtoModel = new Users {id = model. id, AdminPwd = model. adminPwd, AdminAccount = model. adminAccount}; // call SetAuthCookie (dtoModel); // obtain the logon address var returnUrl = Request ["ReturnUrl"]; // determine whether the logon address is null if (! String. isNullOrWhiteSpace (returnUrl) {return Redirect (returnUrl);} else {// return RedirectiToAction return Redirect ("/Home/index");} else {ModelState. addModelError ("", "incorrect account and password"); return View (login) ;}} else {ModelState. addModelError ("", "incorrect input information"); return View (login );}

Cookie for login account

/// <Summary> /// perform cookie on the Logon account /// </summary> /// <param name = "model"> </param> public void SetAuthCookie (users loginModel) {// 1. Convert the object to json var userdata = loginModel. toJson (); // 2. Create a ticket FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (2, "loginUser", DateTime. now, DateTime. now. addDays (1), false, userdata); // encrypt the ticket var tickeEncrypt = FormsAuthentication. encrypt (ticket); // create a Cookie and define HttpCookie = 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 and add the cookie Response. cookies. remove (FormsAuthentication. formsCookieName); Response. cookies. add (cookie );}

3. Add a model file to Models.

Public class loginModels {// <summary> // account // </summary> [DisplayName ("account")] [Required (ErrorMessage = "account cannot be blank")] public string AdminAccount {get; set ;} /// <summary> /// password /// </summary> [DisplayName ("password")] [Required (ErrorMessage = "password cannot be blank")] 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. Obtain the http request through sender // HttpApplication app = new HttpApplication (); // instantiate HttpApplication app = sender as HttpApplication; // 2. Get the http context HttpContext context = app. context; // 3. Obtain the cookie var cookie = context according to FormsAuthe. request. cookies [FormsAuthentication. formsCookieName]; if (cookie! = Null) {// obtain the cookie Value var ticket = FormsAuthentication. Decrypt (cookie. Value); if (! String. isNullOrWhiteSpace (ticket. userData) {// convert a string category to an object model var model = ticket. userData. toObject <AdmininfoViewModel> (); // var acount = model. adminAccount; // get account context. user = new MyFormsPrincipal <AdmininfoViewModel> (ticket, model); // MyFormsPrincipal. identity = new FormsIdentity (ticket); // MyFormsPrincipal. userdata ;}}}

6. log out

Controller

/// <Summary> /// log out /// </summary> public ActionResult loginout () {// Delete the ticket 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 ("exit safely", "loginout", "Users ")

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.