MVC动态页面的权限使用授权属性? [英] MVC Dynamic Page Permissions Using Authorize Attribute?
问题描述
我正在为我公司的网站设置了我的用户权限,而且我们有几个不同的角色和权限,将有被创建。我发现在创建实际的角色和组,以及如何从<一个实现他们一些真棒信息href=\"http://typecastexception.com/post/2013/10/27/Configuring-Db-Connection-and-$c$c-First-Migration-for-Identity-Accounts-in-ASPNET-MVC-5-and-Visual-Studio-2013.aspx\">here.然而,这仍然需要角色是硬coded到authorize标签,有没有办法来动态填充authorize标签,这样我可以有我可以快速地分配不同的权限给不同网站上的网页网页,而不必只回code和修改的权限设置为每一个页面创建?
I'm working on setting up my user permissions for my company's site, and we have several different roles and permissions that will have to be created. I have found some awesome information on creating the actual roles and groups, as well as how to implement them from here. However, this still requires the roles to be hard-coded into the authorize tag, is there a way to dynamically populate the authorize tag, so that I can have a page on the site that I can quickly assign different permissions to different pages, without having to just back into the code and modify the permission set for every single page I create?
推荐答案
执行以下自定义授权属性。
Implement the following custom authorise attribute.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public CustomAuthorizeAttribute (params string[] roleKeys)
{
var roles = new List<string>();
var allRoles = (NameValueCollection)ConfigurationManager.GetSection("CustomRoles");
foreach(var roleKey in roleKeys) {
roles.AddRange(allRoles[roleKey].Split(new []{','}));
}
Roles = string.Join(",", roles);
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new RedirectResult("~/Error/AcessDenied");
}
}
}
然后添加以下到Web.config
Then add the following to the web.config
<section name="CustomRoles" type="System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
和然后,作为一个例子
<CustomRoles>
<add key="UsersPagePermission" value="HR,Accounts,Developers" />
</CustomRoles>
该控制器或者动作,或在全局过滤器(无论你preFER :))添加属性上
The on your controller or action or in the global filters (whichever you prefer :)) add the attribute
例如
[CustomAuthorize("UsersPagePermission")]
public class UserController : Controller
这将允许你修改,而不是code更改权限web.config中。
This will allow you to modify the web.config rather than code to change permissions.
这篇关于MVC动态页面的权限使用授权属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!