MVC Small Business website instance (4)-MVC permission management

Source: Internet
Author: User

There are too few articles related to ASP. net mvc permission management, and even fewer are actually used in project development. Maybe we all use Webform for background development.

Transfer subject:

Module implementation functions:

Role management
-Role addition, deletion, and modification
, Bind users to the role and unbind

Access permission management
-Access permission addition, deletion, and modification

Access permission verification after Logon

Table Design:

 

ControllerAction stores the Controller and Action for which you want to set access permissions. ControllerActionRole
It stores the accessible controllers and actions of corresponding roles, so you don't need to talk about other tables.

Table Association Overview:

The User Role table (UserRole) enables connection binding between the user table (Use) and the Role table (Role). One-to-multiple users can only have one Role.

The Role access permission table (ControllerActionRole) is also in the connection binding relationship between the Role table (Role) and the access permission table (ControllerAction). It is one-to-many, A role can have multiple access permissions.

Design Concept:

When a user logs on to the database, the corresponding role is obtained from the database and saved by Session. Then, the Filter is used to verify the user's access permissions. To improve efficiency, You Can cache data related to access permissions.

Implementation Code:

First, write a Service for determining access permissions.

Public static class AccountService
{
Private static southshopenties1 Service {get {return BaseRepository. sse ;}}
Private static IMsCache MsCache {get {return (IMsCache) MvcApplication. Container ["msCache"] ;}}

Public static bool IsAllowed (Role role, string controllerName, string actionName)
{
IEnumerable <ControllerAction> cas;
If (! MsCache. TryGet ("ControllerActions", out cas ))
{
Try
{
Cas = Service. ControllerActions. ToList ();
Var _ ExpireTime = DateTime. Now. AddMinutes (30); // expire 30 minutes later
MsCache. Set <IEnumerable <ControllerAction> ("ControllerActions", cas, _ ExpireTime );
}
Catch (Exception e)
{
Throw new Exception (e. Message );
}
}


// Obtain the corresponding controller
Var controller = (cas. where (c => c. name = controllerName )). where (c => c. isControler ). select (c => c ). firstOrDefault ();
If (controller! = Null)
{
// Obtain the corresponding action
Var controllerAction = (cas. where (c => c. name = actionName )). where (c => c. isControler = false )). where (c => c. controlerName = controllerName ). select (c => c ). firstOrDefault ();
Return controllerAction = null? IsAllowed (role, controller): IsAllowed (role, controllerAction );
}

Return false;
}

Public static bool IsAllowed (Role role, ControllerAction controllerAction)
{
IEnumerable <ControllerActionRole> cars;
String userCAR = role. RoleId + "_ ControllerActionRole ";
If (! Mscache. tryget (usercar, out cars ))
{
Try
{
Cars = service. controlleractionroles. Where (C => C. roleid = role. roleid). Select (C => C). tolist ();
VaR _ expiretime = datetime. Now. addminutes (30); // expire 30 minutes later
Mscache. Set <ienumerable <controlleractionrole> (usercar, cars, _ expiretime );
}
Catch (exception E)
{
Throw new exception (E. Message );
}
}


// Allow users without a role: that is, allow all users, including users without logon.
If (controlleraction. isallowednoneroles)
{
Return true;
}

// Allow all roles: You can access
If (controlleraction. isallowedallroles)
{
If (role = NULL)
{
Return false;
}

Return true;
}

// Select the role corresponding to the action
VaR roles = cars. Where (C => C. controleractionid = controlleraction. controlleractionid). Select (C => C). tolist ();
If (roles. Count = 0)
{
// The number of roles is 0, that is, no access rule is defined. Access is allowed by default.
Return true;
}

// Search for roles corresponding to the current user
VaR havedrolesids = roles. Find (C => C. roleid = role. roleid );
If (havedrolesids = NULL)
{
// The role corresponding to the current user cannot be found and cannot be accessed
Return false;
}

// Only the allow role can access
If (HavedRolesids. IsAllowed)
{
Return true;
}

Return false;
}
}

 

Then implement the Filter of access permissions and call the above Service.

Public class RoleAuthorizeAttribute: AuthorizeAttribute
{
Public override void OnAuthorization (AuthorizationContext filterContext)
{
Bool isAllowed = false;
Var role = filterContext. HttpContext. Session ["CurrentRole"] as Role;
Var controller = filterContext. RouteData. Values ["controller"]. ToString ();
Var action = filterContext. RouteData. Values ["action"]. ToString ();

If (role! = Null)
Isallowed = accountservice. isallowed (role, controller, action );

If (! Isallowed)
{
Filtercontext. requestcontext. httpcontext. response. Write ("no access permission ");
Filtercontext. requestcontext. httpcontext. response. End ();
}

}
}

If identity authentication is required for the entire controller, put the filter on the outer controller. In this way, you do not need to write on every action. For example:

[RoleAuthorize]
public class AdminController : Controller
{
public ActionResult Index()
{
return View();
}

}

In this way, I will not talk about how to add, delete, or modify permission-related data tables.

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.