ASP.NET MVC - Dynamic Authorization

2019-01-22 03:59发布

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?

3条回答
聊天终结者
2楼-- · 2019-01-22 04:21

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;
    }
}

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.

查看更多
混吃等死
3楼-- · 2019-01-22 04:35

That is exactly what the ASP.NET membership / profile stuff does for you. And it works with the Authorize attribute.

If you want to roll your own you could create a custom action filter that mimics the behavior of the standard Authorize action filter does. Pseudo code below.

public MyAuthorizeAttribute : ActionFilterAttribute
{
    public string MyRole { get; set; }

    public void OnActionExecuting(ControllerContext context)
    {
        if (!(bool)Session["userIsAuthenticated"])
        {
            throw new AuthenticationException("Must log in.");
        }

        if (!Session["userRoles"].Contains(MyRole))
        {
            throw new AuthenticationException("Must have role " + MyRole);
        }
    }
}
查看更多
淡お忘
4楼-- · 2019-01-22 04:40

The role - action relationship must be stored in the database

You will have to check your security within the controller method, unless you want to subclass AuthorizeAttribute so that it looks up the roles from the database for you.

查看更多
登录 后发表回答