ASP.NET MVC - 动态授权 [英] ASP.NET MVC - Dynamic Authorization

查看:189
本文介绍了ASP.NET MVC - 动态授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个简单的CMS,其中在管理面板中动态设置角色。现在授权控制器方法的方法,添加 [Authorize(Roles =admin)] 因此不再足够了。角色操作关系必须存储在数据库中,以便最终用户可以轻松地在管理面板中向/从其他人授予/获取权限。

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?

推荐答案

如果你想控制授权过程,你应该将 AuthorizeAttribute 并覆盖 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;
    }
}

这样做的缺点是,访问ctor注入的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆