In all of my asp.net mvc projects up to this point, permissions to controllers are set by using a custom class based on the [Authorize]
attribute.
However, what if I wanted an administrator role who could grant access to views instead of going through the trouble of having to touch the controller to add/remove roles, re-complile, and push the changes to production. How would I go about doing this?
as discussed. Try the below.
in the controller as I'm sure you're aware.
[PermissionsFilter("CanAccessMyView")]
public ActionResult ReturnMyView ()
{
//etc..
}
Then, in your custom class
public class PermissionsFilter : AuthorizeAttribute
{
private readonly PermissionManager _permissionsManager;
public PermissionsFilter(string permissionName)
{
_permissionName = permissionName;
_permissionsManager = new PermissionServiceManager();
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!_permissionServiceManager.CanAccessPermission(_permissionName))
{
var urlHelper = new UrlHelper(filterContext.RequestContext);
var url = urlHelper.Action("Unauthorised", "Home");
filterContext.Result = new RedirectResult(url);
}
}
}
Where the permissions manager is querying the database or perhaps session info to see if the user user has access.
Hope that helps.