An example tutorial of asp.net MVC Role's Privilege control system

Source: Internet
Author: User
Tags httpcontext reflection ticket

ASP.net MVC explains the method of coarse-grained control permissions through the Onauthorization method of the Authorizeattribute class, followed by the Role-based permission control approach.

Overview of the rights control methods for roles

role-based Privilege Control System RBAC (role Based access control) is the most popular and the most universal privilege controlling system at present. The so-called role-based privilege control, is to group each operation right, each group is a role, for example: The administrator has all the permissions, the editor only has the right to write articles and publish articles, where the "admin" and "edit" is a role-a set of operations permissions. All we need to do is give a role to a user so that the user has a set of permissions under that role.


Now all we have to do is to think of every action under controller as a privilege, and then you can create a role by customizing each permission by using a method, and then mapping the role to the user.

Step of role-based Permission control method

Step one, create a new Roleauthorizeattribute class

This class can get controllername and actionname, which can be based on controllername and actionname to determine what kind of operation, such as the following code

The code is as follows Copy Code

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.Security;
Using SYSTEM.WEB.MVC;
Using System.Web.Routing;

Namespace Samplemvcwebsite
{
public class Roleauthorizeattribute:authorizeattribute
{
public override void Onauthorization (AuthorizationContext filtercontext)
{
var Isauth = false;
if (!filtercontext.requestcontext.httpcontext.request.isauthenticated)
{
Isauth = false;
}
Else
{
if (filterContext.RequestContext.HttpContext.User.Identity!= null)
{
var roleapi = new Roleapi ();
var actiondescriptor = Filtercontext.actiondescriptor;
var controllerdescriptor = Actiondescriptor.controllerdescriptor;
var controller = Controllerdescriptor.controllername;
var action = Actiondescriptor.actionname;
var ticket = (filterContext.RequestContext.HttpContext.User.Identity as formsidentity). Ticket;
var role = Roleapi.getbyid (ticket. Version);
if (role!= null)
{
Isauth = role. Permissions.any (x => x.permission.controller.tolower () = Controller. ToLower () && x.permission.action.tolower () = Action. ToLower ());
}
}
}
if (!isauth)
{
Filtercontext.result = new Redirecttorouteresult (new RouteValueDictionary (New {controller = "account", action = "Login", ReturnUrl = filterContext.HttpContext.Request.Url, ReturnMessage = "You do not have permission to view."});
Return
}
Else
{
Base. Onauthorization (Filtercontext);
}
}
}
}

Roleapi is the API for role object management, where you need to set up your own role management. Controllername and ActionName are available in the above code through the controllerdescriptor of the Filtercontext Actiondescriptor object. When you get to the role of the current user, you can implement permission validation by viewing whether the user's permissions contain methods in the currently accessed controller. The main use of Actiondescriptor and Controllerdescriptor, the introduction of these two classes can refer to the MSDN official website.

PS: Here we use ticket version to store Roleid. You can also do it in other ways. Information about ticket can be referenced in the official Microsoft MSDN documentation, which is no longer Aushu.

Step two, create the DescriptionAttribute class

This class is an inheritance attribute in order to give the action method a description tag, such as the following code

The code is as follows Copy Code

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;

Namespace Samplemvcwebsite
{
   ///<summary>
   ///Description Attribute
   ///</summary>
    public class DescriptionAttribute: Attribute
    {
        public string Name
         {
            set;
            get;
       }
        public int No
        {
            set;
            get;
       }
   }
}

The name and no and permission classes are Controllername, ActionName, and Controllerno, and Actionno are corresponding.

Step three, give controllers a DescriptionAttribute label.

Use the DescriptionAttribute label created by step two to mark the controller to get information when storing the permission. As in the following code:

The code is as follows Copy Code

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;

Namespace Samplemvcwebsite.controllers
{
[Description (No = 1, Name = "user")]
public class Usercontroller:controller
{
[Roleauthorize]
[Description (No = 1, Name = "User First page")]
Public ActionResult Index ()
{
return View ();
}
[Roleauthorize]
[Description (No = 1, Name = "user admin")]
Public ActionResult Manage ()
{
return View ();
}
[Roleauthorize]
[Description (No = 1, Name = "user Details")]
Public ActionResult Detail ()
{
return View ();
}
}
}

Step four, build permission control List

Step one has a role. Permissions, this Permissions is the set of permissions that the current user has, and is stored in the Database relational table in the actual project development, we can define the Permissions class as the following code

The code is as follows Copy Code

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Namespace Samplemvcwebsite
{
public class Permission
{
<summary>
Permission Id
</summary>
public virtual int Id
{
Set
Get
}
<summary>
Permission Action No
</summary>
public virtual int Actionno
{
Set
Get
}

<summary>
Controller No
</summary>
public virtual int Controllerno
{
Set
Get
}

<summary>
Controller Name
</summary>
Public virtual String Controllername
{
Set
Get
}

<summary>
Permission Action Name
</summary>
Public virtual String ActionName
{
Set
Get
}

<summary>
Controller
</summary>
Public virtual String Controller
{
Set
Get
}

<summary>
Action
</summary>
Public virtual String Action
{
Set
Get
}
}
}

Property controller and Action records are permissions, Controllername and ActionName are used to display Ui,controllerno and Actionno to display sequential control. The rest is well understood according to the code comments above and is not stated here.

So you need to input the action into the database to implement ROLEAPI. Manual input If the method is less good, but more than the trouble, so we can use. NET's reflection mechanism to create the permissions. First look at the following code:

The code is as follows Copy Code

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;
Using Samplemvcwebsite.controllers;

Namespace Samplemvcwebsite
{
public class Installcontroller
{
public class Installcontroller:controller
{
Public ActionResult Index ()
{
return View ();
}

[HttpPost]
Public ActionResult Index ()
{
Try
{
var roleservice = new Roleapi ();
#region Init permission
CreatePermission (New Usercontroller ());
#endregion

var alldefinedpermissions = roleservice.getdefinedpermissions ();

#region Administrator Role Initialization
var adminpermissions = new list<rolepermissioninfo> ();
foreach (var d in alldefinedpermissions)
{
Adminpermissions.add (new Rolepermissioninfo {Permission = d,});
}
int Adminroleid = roleservice.addrole (New Roleinfo
{
Name = "Administrator",
Description = "",
Permissions = Adminpermissions,
Adddate = DateTime.Now,
});
#endregion
Return redirecttoaction ("Admin", "Index");
}
catch (Exception ex)
{
Modelstate.addmodelerror ("", ex. message);
return View ();
}
}
private void CreatePermission (Controller customcontroller)
{
var roleapi = new Roleapi ();

var controllername = "";
var controller = ""; var controllerno = 0;
var actionname = ""; var action = ""; var Actionno = 0;
var controllerdesc = new keyvaluepair<string, int> ();

var controllertype = Customcontroller.gettype ();

Remove Controller Posfix
Controller = ControllerType.Name.Replace ("Controller", "");
Controllerdesc = GetDesc (Controllertype);
if (!string. IsNullOrEmpty (Controllerdesc.key))
{
Controllername = Controllerdesc.key;
Controllerno = Controllerdesc.value;
foreach (var m in Controllertype.getmethods ())
{
var mdesc = Getpropertydesc (m);
if (string. IsNullOrEmpty (Mdesc.key)) continue;
action = M.name;
ActionName = Mdesc.key;
Actionno = Mdesc.value;
Roleapi.createpermissions (Actionno, Controllerno, ActionName, Controllername, Controller, action);
}
}
}
Private keyvaluepair<string, int> getdesc (type type)
{
var DescriptionAttribute = (DescriptionAttribute) (type. GetCustomAttributes (False). FirstOrDefault (x => x is DescriptionAttribute));
if (DescriptionAttribute = null) return to New keyvaluepair<string, int> ();
return new keyvaluepair<string, int> (Descriptionattribute.name, descriptionattribute.no);
}
Private keyvaluepair<string, int> getpropertydesc (System.Reflection.MethodInfo type)
{
var DescriptionAttribute = (DescriptionAttribute) (type. GetCustomAttributes (False). FirstOrDefault (x => x is DescriptionAttribute));
if (DescriptionAttribute = null) return to New keyvaluepair<string, int> ();
return new keyvaluepair<string, int> (Descriptionattribute.name, descriptionattribute.no);
}
}
}
}

The above code first obtains the description of the controller by GetDesc, the Getpropertydesc method obtains the description of the method, the method here is an independent permission, Then, through the Roleapi createpermissions method, the data of the permission is written to the database, the code that writes the data to the database needs to be implemented according to its own database reading and writing method, and it is highly recommended to read and write the database using LINQ. It then gets all the permissions through the ROLEAPI and binds all permissions to the Admin role, saving the corresponding relationship. This completes the permission control List generation and initializes the administrator user.

The above example allows you to complete the asp.net MVC role-based permission control system, in which the ROLEAPI requires you to write code to implement the operation of the database, which is the permissions, roles, user data tables, and the role of the rights month and the relationship table of roles and users.

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.