A detailed tutorial on implementing the user logon and permission verification module of the asp.net MVC4 framework website from scratch, asp. netmvc4

Source: Internet
Author: User

A detailed tutorial on implementing the user logon and permission verification module of the asp.net MVC4 framework website from scratch, asp. netmvc4
User logon and permission verification are an indispensable part of the website function. The asp.net MVC4 framework has built-in class libraries for implementing this function. You only need to build a simple library to complete this function.

The following describes how to complete this function in detail. The source code of the instance is downloaded at the end, hoping to provide a reference for a friend who is new to MVC.

Step 1: Install the MVC4 framework for

VS2012 comes with the MVC4 framework. Other versions can be installed using an independent installation package. We will not discuss it here. This example is created using VS2013,. NET4.0 + MVC4

Step 2: Create an MVC4 website project

Select File-New-project, and create an empty MVC website according to the example.

 

 

Step 3: Configure web. config and enable Form verification.

Open web. config in the root directory, insert code under the <system. web> node, enable Form verification, and specify the default logon page

<authentication mode="Forms">      <forms loginUrl="/Home/Login" timeout="2880"/></authentication>

 

 

Step 4: create the required file 

In this example, you need to create the following files:

LoginModel. cs in the Model folder

HomeController. cs in the Controllers folder

Under View, create the Home directory and under the folder:

Index. cshtml

Login. cshtml

Show. cshtml

Edit. cshtml

Add. cshtml

Shows the file structure:

 

Step 5: Fill in the LoginModel code

Public class LoginModel {[Display (Name = "UserName")] [Required (ErrorMessage = "UserName cannot be blank")] public string UserName {get; set ;} [Display (Name = "password")] [Required (ErrorMessage = "password cannot be blank")] [DataType (DataType. password)] [RegularExpression (@ "^ \ w + $", ErrorMessage = "Incorrect Password format, only letters, numbers, or underscores")] public string Password {get; set ;} [Display (Name = "Remember to log on? ")] Public bool RememberMe {get; set;} public string Login () {// compare the user name and password from the database, and get the user permission list // here, In order to simply compare strings and return the permission list, if NULL is returned, the user name or password is incorrect. // The permission list is used, split permission name string result = null; if (this. userName = "guest" & this. password = "guest") result = "Add"; if (this. userName = "admin" & this. password = "admin") result = "Add, Edit"; return result ;}}

 


When copying the code above to the class, VS's smart awareness will prompt you that the following namespace is missing. Just add it.

using System.ComponentModel.DataAnnotations;

 

Step 5: Fill in the HomeControll code

Public class HomeController: Controller {// GET:/Home/public ActionResult Index () {ViewBag. info = "this page does not contain permission annotations and can be accessed by all users. "; return View ();} [Authorize (Roles =" Edit ")] // This annotation indicates that only users with the Edit permission can access public ActionResult Edit () {ViewBag. info = "this page can be accessed by anyone who needs the Edit permission. "; return View ();} [Authorize (Roles =" Add ")] // This annotation indicates that only users with the Add permission can access public ActionResult Add () {ViewBag. info = "this page can be accessed by anyone who needs the Add permission. "; Return View ();} [Authorize (Roles = "Add, Edit")] // This annotation indicates that only users with the Add permission can access public ActionResult Show () {ViewBag. info = "this page can be accessed by anyone who needs the Edit or Add permissions. "; return View ();} public ActionResult Login (LoginModel model) {return View ();} [HttpPost] // This annotation indicates only receiving Post data [ValidateAntiForgeryToken] // This annotation can prevent cross-site attacks [ActionName ("Login")] // This annotation can be used to change the Action name public ActionResult LoginCheck (LoginModel model) {if (! ModelState. isValid) {// enter the server for verification. If the verification fails, the following code is displayed: return View () in this example;} string result = model. login (); if (result = null) {// if the user name or password is incorrect, the code is skipped in this example. return View ();} else {// enter the core code FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket (1, model. userName, DateTime. now, DateTime. now. addHours (240), // remember the password time model. rememberMe, // whether to save the cookie. Remember the password result // The user permission list obtained is a comma-separated string); string encryptedTickt = FormsAuthentication. encrypt (authTicket); HttpCookie authCookie = new HttpCookie (FormsAuthentication. formsCookieName, encryptedTickt); Response. cookies. add (authCookie); Response. redirect ("/Home", true); ActionResult empty = new EmptyResult (); return empty;} return View ();}

 


 

Copy the above Code and you will be prompted to add the following namespace:

Using ChengChenXu. MVC4_Login_Demo.Models; // project Model namespace using System. Web. Security;

 

Step 6: Fill in the View code. The following code only shows the content inside the <Body> tag, and the page header is not displayed (it is completely in the source code ).

Index. cshtml

<H1> @ ViewBag. info 

 


Add. cshtml Edit. cshtml Show. cshtml three files have the same code

<H1> @ ViewBag. Info 

 


Login. cshtml this file must first add a line of code at the top, indicating that it is a strong type View

@model ChengChenXu.MVC4_Login_Demo.Models.LoginModel

 

Page code:

@ Using (Html. beginForm () {@ Html. antiForgeryToken () @ Html. labelFor (model => model. userName) @ Html. textBoxFor (model => model. userName) <br/> @ Html. labelFor (model => model. password) @ Html. passwordFor (model => model. password) <br/> @ Html. labelFor (Model => Model. rememberMe) @ Html. checkBoxFor (model => model. rememberMe) <br/> <input type = "submit" class = "submit" tabindex = "3" value = "Logon"/>}

 


Step 7: modify the code of Global. asax in the root directory, add the permission processing code, and copy and add the following two methods to the Global file.

     public MvcApplication()        {            AuthorizeRequest += new EventHandler(MvcApplication_AuthorizeRequest);        }         void MvcApplication_AuthorizeRequest(object sender, EventArgs e)        {            var id = Context.User.Identity as FormsIdentity;            if (id != null && id.IsAuthenticated)            {                var roles = id.Ticket.UserData.Split(',');                Context.User = new GenericPrincipal(id, roles);            }        }

 

After copying, the following namespace is missing:

using System.Web.Security;using System.Security.Principal;

 

After all the instances are completed, run the following command.

No permission is required for/Home on the Home page.

The logon page is/Home/Login.No permission required

The Add permission is required for the/Home/Add page.

The Edit or Add permission is required for/Home/Show on the display page.

The Edit permission is required for/Home/Edit on the editing page.

Two built-in accounts

Account and password Permissions

Guest "add"

Admin "add, edit"

 

Running result:

If you directly access pages other than the Home and Login pages (pages requiring permissions), the Login page is displayed.

The guest account can access the Add Show page.

Admin account can access the Add Edit Show page

 

Icing on the cake:

1. When you automatically jump to the logon page, the URL will have a ReturnUrl parameter record before the jump, which can capture this page and jump back after login.

2. MVC supports client verification and requires support for js files, so that the client no longer needs to write JavaScript code for input verification. This example is not displayed. Please search for it by yourself.

 

This blog post

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.