Asp.net mvc verifies the Forms Implementation of user logon, mvcforms

Source: Internet
Author: User

Asp.net mvc verifies the Forms Implementation of user logon, mvcforms

Here, we use the AuthorizeAttribute filter that comes with asp.net mvc to verify the user's identity. You can also use a custom filter. The steps are the same.

Step 1: Create an asp.net mvc project. There is a FilterConfig. cs under the App_Start folder of the project. You can register a global filter in this file. Add the AuthorizeAttribute filter to the file as follows:

Public class FilterConfig {public static void RegisterGlobalFilters (GlobalFilterCollection filters) {filters. add (new handleerrorattriters (); // Add the built-in permission filter to the global filter. add (new System. web. mvc. authorizeAttribute ());}}

Step 2: Modify the website Authentication mode = "Forms" in the web. config configuration file"

<System. web> <! -- Cockie name: the url to jump to when not logged in --> <authentication mode = "Forms"> <forms name = "xCookie" loginUrl = "~ /Login/Index "protection =" All "timeout =" 60 "cookieless =" UseCookies "> </forms> </authentication> <compilation debug =" true "targetFramework =" 4.5 "/> 

Tip: configure the name value as the name of the final generated cookie. loginUrl specifies the page to jump to when the user is not logged in. The logon page is challenged here.

Step 3: Add controllers and views related to user login

Create a LoginController controller:

Public class LoginController: Controller {[HttpGet] [AllowAnonymous] public ActionResult Index () {return View ();} [HttpPost] [AllowAnonymous] public ActionResult Login (User user) {if (! User. Username. Trim (). Equals ("liuxin") |! User. password. trim (). equals ("abc") {ModelState. addModelError ("", "Incorrect username or password"); return View ("index", user) ;}// if (! User. username. trim (). equals ("liuxin") {// ModelState. addModelError ("Username", "Username error"); // return View ("index", user); //} // if (! User. password. trim (). equals ("abc") {// ModelState. addModelError ("Password", "Incorrect Password"); // return View ("index", user); //} user. id = Guid. newGuid (). toString ("D"); // manually set a user ID for testing FormsAuthHelp. addFormsAuthCookie (user. id, user, 60); // set the ticket name to the user id and the effective time to 60 minutes return Redirect ("~ ");} [HttpGet] public ActionResult Logout () {FormsAuthHelp. RemoveFormsAuthCookie (); return Redirect ("~ /Login/Index ");}}

Note: "[AllowAnonymous]" must be used for the Index and Login methods to indicate that these two methods can be accessed anonymously. Otherwise, because the filter does not allow anonymous access, the logon page and user submission cannot be performed. Obviously this is not what we want to see.

Tip: For the convenience of testing, the user data is written to death, and the user id is also generated temporarily

   public class User    {        public string Id { get; set; }        public string Username { get; set; }        public string Password { get; set; }    }

Create a logon View:

@ {Layout = null; ViewBag. title = "Index" ;}< h3> you have not logged in. Please log in 

Tip: if the user is not logged on, the system jumps to the web. the url page configured in config. When the user enters the password and submits the data, the data entered by the user is submitted to the Login method under the LoginController controller to verify the user's input, if the authentication fails, return to the logon interface. When the authentication succeeds

<*** FormsAuthHelp. addFormsAuthCookie (user. id, user, 60); // set the ticket name to the user id and the effective time to 60 minutes ***>, the purpose of this statement is to generate a ticket and encapsulate it in the cookie. asp.net mvc officially checks whether the cookie authenticates the user to log on. The specific code is as follows:

Step 4: encapsulate user information generation ticket into cookies

Public class FormsAuthHelp {// <summary> // Add the ticket generated by the currently logged-on user to the cookie (used for login) /// </summary> /// <param name = "loginName"> User name associated with the Forms authentication ticket (generally the id of the current user, used as the name of the ticket) </param> /// <param name = "userData"> User Information </param> /// <param name = "expireMin"> validity period </param> public static void addFormsAuthCookie (string loginName, object userData, int expireMin) {// serialize the currently logged-in user information var data = JsonConvert. serializeObjec T (userData); // create a FormsAuthenticationTicket that contains the login name and additional user data. Var ticket = new FormsAuthenticationTicket (1, loginName, DateTime. Now, DateTime. Now. AddDays (1), true, data); // encrypt Ticket to an encrypted string. Var cookieValue = FormsAuthentication. encrypt (ticket); // create a logon Cookie Based on the encryption result // FormsAuthentication. formsCookieName is the cookie name specified in the configuration file. The default value is ". ASPXAUTH "var cookie = new HttpCookie (FormsAuthentication. formsCookieName, cookieValue) {HttpOnly = true, Secure = FormsAuthentication. requireSSL, Domain = FormsAuthentication. cookieDomain, Path = FormsAuthentication. formsCookiePath}; // set the effective time if (expireMin> 0) cookie. expires = DateTime. now. addMinutes (expireMin); var context = HttpContext. current; if (context = null) throw new InvalidOperationException (); // write the logon Cookie context. response. cookies. remove (cookie. name); context. response. cookies. add (cookie) ;}//< summary> /// Delete the user's ticket /// </summary> public static void RemoveFormsAuthCookie () {FormsAuthentication. signOut ();}}

Step 5: test execution

1. Start the website and enter the corresponding URL, as shown in figure

  

2. If you have not logged on to the console, you will be redirected to the logon page, as shown in figure

  

3. Entering the wrong password will redirect to the logon page again and prompt for an error

  

4. Enter the correct user name and password

  

5. clicking the user exit will delete the cookie, and the logon page will be displayed.

 

Test source code: Link: https://pan.baidu.com/s/1cm722q password: ut53

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.