ASP. net mvc: Form authentication and role permission management example, mvc permission management

Source: Internet
Author: User

ASP. net mvc: Form authentication and role permission management example, mvc permission management

Based on ASP. net mvc, many ASP. NET features (such as form authentication and membership) can be directly used in MVC. This article aims to provide code that can be referenced and does not involve too much theoretical knowledge.

This document only uses ASP. NET does not use its Membership and role management (RoleManager) for form authentication. There are two reasons: one is not flexible, and the other is not closely related to MVC.

I. Example Project

User. cs is a model file that contains the User class:

public class User{    public int ID { get; set; }    public string Name { get; set; }    public string Password { get; set; }    public string[] Roles { get; set;  }}

UserRepository is a data access class. For demonstration convenience, it does not connect to the database, but uses an array as the Data source:

public class UserRepository{    private static User[] usersForTest = new[]{        new User{ ID = 1, Name = "bob", Password = "bob", Roles = new []{"employee"}},        new User{ ID = 2, Name = "tom", Password = "tom", Roles = new []{"manager"}},        new User{ ID = 3, Name = "admin", Password = "admin", Roles = new[]{"admin"}},    };    public bool ValidateUser(string userName, string password)    {        return usersForTest            .Any(u => u.Name == userName && u.Password == password);    }    public string[] GetRoles(string userName)    {        return usersForTest            .Where(u => u.Name == userName)            .Select(u => u.Roles)            .FirstOrDefault();    }    public User GetByNameAndPassword(string name, string password)    {        return usersForTest            .FirstOrDefault(u => u.Name == name && u.Password == password);    }}
Ii. User logon and authentication method 1

Modify AccountController:The original AccountController abstracts form authentication in order to implement control inversion. To facilitate the demonstration, I will remove this part (and register and change the password ):

Public class AccountController: Controller {private UserRepository repository = new UserRepository (); public ActionResult LogOn () {return View ();} [HttpPost] public ActionResult LogOn (LogOnModel model, string returnUrl) {if (ModelState. isValid) {if (repository. validateUser (model. userName, model. password) {FormsAuthentication. setAuthCookie (model. userName, model. rememberMe); if (! String. isNullOrEmpty (returnUrl) return Redirect (returnUrl); else return RedirectToAction ("Index", "Home");} else ModelState. addModelError ("", "incorrect user name or password! ") ;}Return View (model) ;}public ActionResult LogOff () {FormsAuthentication. SignOut (); return RedirectToAction (" Index "," Home ");}}

Modify Global. asax:

public class MvcApplication : System.Web.HttpApplication{    public MvcApplication()    {        AuthorizeRequest += new EventHandler(MvcApplication_AuthorizeRequest);    }    void MvcApplication_AuthorizeRequest(object sender, EventArgs e)    {        IIdentity id = Context.User.Identity;        if (id.IsAuthenticated)        {            var roles = new UserRepository().GetRoles(id.Name);            Context.User = new GenericPrincipal(id, roles);        }    }    //...}

Add constructor to MvcApplication and add the handler for the AuthorizeRequest event.

Method 2

In this way, the user role is saved to the user Cookie and FormsAuthenticationTicket is used.

Modify AccountController:

Public class AccountController: Controller {private UserRepository repository = new UserRepository (); public ActionResult LogOn () {return View ();} [HttpPost] public ActionResult LogOn (LogOnModel model, string returnUrl) {if (ModelState. isValid) {User user = repository. getByNameAndPassword (model. userName, model. password); if (user! = Null) {FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1, user. name, DateTime. now, DateTime. now. add (FormsAuthentication. timeout), model. rememberMe, user. roles. aggregate (I, j) => I + "," + j); HttpCookie cookie = new HttpCookie (FormsAuthentication. formsCookieName, FormsAuthentication. encrypt (ticket); Response. cookies. add (cookie); if (! String. isNullOrEmpty (returnUrl) return Redirect (returnUrl); else return RedirectToAction ("Index", "Home");} else ModelState. addModelError ("", "incorrect user name or password! ") ;}Return View (model) ;}public ActionResult LogOff () {FormsAuthentication. SignOut (); return RedirectToAction (" Index "," Home ");}}

Modify Global. asax:

public class MvcApplication : System.Web.HttpApplication{    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);        }    }    //...}
Iii. Role Permissions

After using any method, we can use AuthorizeAttribute in the Controller to Implement role-based permission management:

[Authorize(Roles = "employee,manager")]public ActionResult Index1(){    return View();}[Authorize(Roles = "manager")]public ActionResult Index2(){    return View();}[Authorize(Users="admin", Roles = "admin")]public ActionResult Index3(){    return View();}
Iv. Brief Description

MVC uses the HttpContext. User attribute for identity authentication and role management. Similarly, AuthorizeAttribute also performs role permission Verification Based on HttpContext. User.

Because it is not recommended to save the relevant user information in the Session after the user logs on (this is often seen on the Internet), it is very bad to save the user information in the Session.

Do not judge role permissions in Action. Use AuthorizeAttribute or its subclass. The following methods are incorrect:

public ActionResult Action1(){    if (Session["User"] == null) { /**/}    /**/}public ActionResult Action2(){    if (User.Identity == null) { /**/}    if (User.Identity.IsAuthenticated == false) { /**/}    if (User.IsInRole("admin") == false) { /**/}    /**/}

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.