ASP.NET MVC - 动态授权 [英] ASP.NET MVC - Dynamic Authorization
问题描述
我建立一个简单的CMS中的角色是在管理面板动态设置。授权一个控制器方法,将现有的方法 [授权(角色=管理员)]
例如,因此不再足够。该角色的动作关系必须存储在数据库中,使最终用户可以轻松地从别人的管理面板给/取权限/。我怎样才能实现呢?
I am building a simple CMS in which roles are set dynamically in the admin panel. The existing way of authorizing a controller method, adding [Authorize(Roles="admin")]
for example, is therefore no longer sufficient. The role-action relationship must be stored in the database, so that end users can easily give/take permissions to/from others in the admin panel. How can I implement this?
推荐答案
如果你想利用授权过程的控制,你应该继承<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx\">AuthorizeAttribute并重写<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.authorizecore%28v=VS.90%29.aspx\">AuthorizeCore方法。然后,只需用你的 CmsAuthorizeAttribute
而不是默认的装饰你的控制器。
If you want to take control of the authorization process, you should subclass AuthorizeAttribute and override the AuthorizeCore method. Then simply decorate your controllers with your CmsAuthorizeAttribute
instead of the default.
public class CmsAuthorizeAttribute : AuthorizeAttribute
{
public override virtual bool AuthorizeCore(HttpContextBase httpContext)
{
IPrincipal user = httpContext.User;
IIdentity identity = user.Identity;
if (!identity.IsAuthenticated) {
return false;
}
bool isAuthorized = true;
// TODO: perform custom authorization against the CMS
return isAuthorized;
}
}
这样做的缺点是,你将无法访问构造函数注入的IoC,所以你必须从容器直接请求任何依赖关系。
The downside to this is that you won't have access to ctor-injected IoC, so you'll have to request any dependencies from the container directly.
这篇关于ASP.NET MVC - 动态授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!