Customize authorizeattribute to implement MVC permission Design

Source: Internet
Author: User
ArticleDirectory
    • Concise requirements
    • Database Design
    • Core Process
    • Test

This document introduces you:Customize authorizeattribute to implement MVC permission Design, MainlyRoles and controllers, Action, and other parameter associations to determine user permissions, and then passCustom authorizeattributeTo implement this function, and some rules will be adjusted according to the situation. See the following content:

 

Concise requirements

1. Permission control can be implemented for each action and can be dynamically configured in the database

2. permissions can be divided into: allow access by all users, allow access by registered users, and allow/prohibit access by specific users

 

Database Design

 

The database is not used in the demo. The corresponding table class is provided here.

///// Controller and action /// public class controlleraction {public int ID {Get; set;} public string name {Get; set ;} //// iscontroller indicates whether it is a controller. If it is set to false, /// indicates that it is an action, the controllername field comes in handy. // public bool iscontroller {Get; set;} // controller name // If iscontroller is false, this item cannot be blank // Public String controllname {Get; set ;} ///// indicates whether to allow access by unauthorized persons. // public bool isallowednoneroles {Get; set ;} ///// whether to allow access by persons with roles /// public bool isallowedallroles {Get; Set ;}} ///// table associated with the user and role /// public class controlleractionrole {public int ID {Get; set ;} ///// corresponding controlleraction No. // public int controlleractioid {Get; set ;} ///// corresponding role ID // public int roleid {Get; set ;} ///// isallowed indicates whether the user with the roleid has the permission to access controlleractioid ///Public bool isallowed {Get; set ;}} ///// role // public class role {public int ID {Get; set;} public string name {Get; set;} Public String description {Get; set ;}///// user /// public class user {public int ID {Get; set;} public string name {Get; Set ;}} ///// table associated with the user and role /// public class userrole {public int ID {Get; set;} public int userid {Get; set ;} public int roleid {Get; set ;}}
Core Process

 

We can see a database class to simulate a database.

//////// Simulate database /// public class database {public static list users; public static list roles; public static list userroles; public static list controlleractions; public static list controlleractionroles; static database () {// initialize User Users = new list () {new user () {id = 1, name = "admin "}, new User () {id = 2, name = "user"}, new user () {id = 3, name = "guest" }}; roles = new list () {New Role () {id = 1, name = "Administrator"}, new role () {id = 2, name = "user" }}; userroles = new list () {New userrole () {id = 1, roleid = 1, userid = 1}, // administrator new userrole () {id = 2, roleid = 2, userid = 2} // user}; controlleractions = new list () {New controlleraction () {id = 1, name = "Index", iscontroller = true, isallowednoneroles = true, isallowedallroles = true}, // home allows everyone to access new controlleraction () {id = 2, controllname = "home", name = "admin", iscontroller = false, isallowednoneroles = false, isallowedallroles = false}, // The Home/admin administrator can access new controlleraction () {id = 3, controllname = "home", name = "user ", iscontroller = false, isallowednoneroles = false, isallowedallroles = true}, // home/users with roles can access new controlleraction () {id = 4, controllname = "home ", name = "useronly", iscontroller = false, isallowednoneroles = false, isallowedallroles = false}, // home/useronly users can access}; controlleractionroles = new list () {New controlleractionrole () {id = 1, controlleractioid = 2, roleid = 1, isallowed = true}, // The administrator can access new controlleractionrole () {id = 2, controlleractioid = 4, roleid = 2, isallowed = true} // user can be accessed };}}

here's the main Code

///// Custom authorizeattribute // public class userauthorizeattribute: authorizeattribute {public override void onauthorization (authorizationcontext filtercontext) {var user = filtercontext. httpcontext. session ["currentuser"] As user; // the user is empty and guest if (user = NULL) {user = database is assigned. users. find (u => U. name = "guest");} var controller = filtercontext. routedata. values ["controller"]. tostring (); VaR action = filtercontext. routedata. Values ["action"]. tostring (); var isallowed = This. isallowed (user, controller, action); If (! Isallowed) {filtercontext. requestcontext. httpcontext. response. write ("no access permission"); filtercontext. requestcontext. httpcontext. response. end () ;}///// determine whether access is allowed //////   User ///  Controller ///   Action // whether to allow access to public bool isallowed (User user, string controller, string action) {// find controlleraction var controlleraction = database. controlleractions. find (CA => Ca. iscontroller = false & Ca. name = Action & Ca. controllname = Controller); // action has no record. Find controller if (controlleraction = NULL) {controlleraction = database. controlleractions. find (CA => Ca. iscontroller & Ca. name = controll Er);} // no rule if (controlleraction = NULL) {return true;} // allow users without roles: that is, allow all users, including users without logon if (controlleraction. isallowednoneroles) {return true;} // allow all roles: If a role exists, you can access if (controlleraction. isallowedallroles) {var roles = database. userroles. findall (UR => ur. userid = user. ID); If (roles. count> 0) {return true;} else {return false;} // select the role var actionroles = database corresponding to the action. controllera Ctionroles. findall (CA => Ca. controlleractioid = controlleraction. ID ). tolist (); If (actionroles. count = 0) {// The number of roles is 0, that is, no access rule is defined. Return true is allowed by default;} var userhavedrolesids = database. userroles. findall (UR => ur. userid = user. ID ). select (CA => Ca. roleid ). tolist (); // find the role var notallowedroles = actionroles. findall (r =>! R. isallowed ). select (CA => Ca. roleid ). tolist (); If (notallowedroles. count> 0) {foreach (INT roleid in notallowedroles) {// the user's role cannot access if (userhavedrolesids. contains (roleid) {return false ;}}// find the list of permitted roles var allowroles = actionroles. findall (r => r. isallowed ). select (CA => Ca. roleid ). tolist (); If (allowroles. count> 0) {foreach (INT roleid in allowroles) {// If (userhavedrolesids. contains (roleid) {return true ;}}// Access prohibited by default return false ;}}
Test
[Handleerror] [userauthorize] public class homecontroller: controller {public actionresult index () {viewdata ["message"] = "Welcome to ASP. net mvc! "; Return view ();} public actionresult admin () {viewdata [" message "] =" only the administrator can access! "; Return view (" Index ");} public actionresult user () {viewdata [" message "] =" can be accessed as long as it is a registered user! "; Return view (" Index ");} public actionresult useronly () {viewdata [" message "] =" can only be accessed by a user! "; Return view (" Index ");} public actionresult login (string user) {session [" currentuser "] = database. users. find (u => U. name = user); If (session ["currentuser"]! = NULL) {viewdata ["message"] = "you have logged on as" + User;} return view ("Index");} public actionresult about () {return view ();}}

 

1. Log On As Admin

 

Access Admin

 

Access user

 

Access useronly

 

2. Log On As a user

 

Access Admin

 

Access user

Access useronly

 

Download mvcrole.rar from demo

Article contentCustomize authorizeattribute to implement MVC permission DesignNow, you can find the source code.

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.