Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Dynamic Authorization

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?

like image 585
xantrus Avatar asked Mar 07 '10 20:03

xantrus


1 Answers

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.

like image 106
Richard Szalay Avatar answered Sep 20 '22 10:09

Richard Szalay