开发者

ASP.Net MVC how to determine if a user can access a URL?

开发者 https://www.devze.com 2022-12-19 16:26 出处:网络
So I was reading another question regarding login loop when you have a user logging in, set to return to a URL which they might not have access to after logging in (ie. an admin page, and the user log

So I was reading another question regarding login loop when you have a user logging in, set to return to a URL which they might not have access to after logging in (ie. an admin page, and the user logs in with a normal account).

The solution under WebForms seems to be to utilize the UrlAuthorizationModule.CheckUrlAccessForPrincipal method. However that does not work for URLs going to Action Methods secured with the Authorize Attribute. I figured I could work out which method the URL was pointing at and reflect over it to solve my problem - but I can't seem to work out how I g开发者_Go百科et this information out of the routing table.

Anyone ever worked with this, or have a solution for this? If I can just get hold of the route information from a URL I think I could work the rest out, but if anyone has a generic solution - ie. some hidden method akin to the before mentioned one for MVC, then that would be totally awesome as well.

I'm not asking how to check if the User has acces to a specified Controller/Action pair. I first and foremost need to work out how to get the Controller/Action pair from the RouteTable based off the URL. The reason for all the background story, is in case that there does indeed exist an equivalent to UrlAuthorizationModule.CheckUrlAccessForPrincipal for MVC.


John Farrell (jfar)'s answer (SecurityTrimmingExtensions class) updated for MVC 4:

public static class SecurityCheck
{
    public static bool ActionIsAuthorized(string actionName, string controllerName)
    {
        IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
        ControllerBase controller = factory.CreateController(HttpContext.Current.Request.RequestContext, controllerName) as ControllerBase;
        var controllerContext = new ControllerContext(HttpContext.Current.Request.RequestContext, controller);
        var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
        var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);
        AuthorizationContext authContext = new AuthorizationContext(controllerContext, actionDescriptor);
        foreach (var authAttribute in actionDescriptor.GetFilterAttributes(true).Where(a => a is AuthorizeAttribute).Select(a => a as AuthorizeAttribute))
        {
            authAttribute.OnAuthorization(authContext);
            if (authContext.Result != null)
                return false;
        }
        return true;
    }
}


I ported and hacked this code from the MvcSitemap:

public static class SecurityTrimmingExtensions 
{

    /// <summary>
    /// Returns true if a specific controller action exists and
    /// the user has the ability to access it.
    /// </summary>
    /// <param name="htmlHelper"></param>
    /// <param name="actionName"></param>
    /// <param name="controllerName"></param>
    /// <returns></returns>
    public static bool HasActionPermission( this HtmlHelper htmlHelper, string actionName, string controllerName )
    {
        //if the controller name is empty the ASP.NET convention is:
        //"we are linking to a different controller
        ControllerBase controllerToLinkTo = string.IsNullOrEmpty(controllerName) 
                                                ? htmlHelper.ViewContext.Controller
                                                : GetControllerByName(htmlHelper, controllerName);

        var controllerContext = new ControllerContext(htmlHelper.ViewContext.RequestContext, controllerToLinkTo);

        var controllerDescriptor = new ReflectedControllerDescriptor(controllerToLinkTo.GetType());

        var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);

        return ActionIsAuthorized(controllerContext, actionDescriptor);
    }


    private static bool ActionIsAuthorized(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        if (actionDescriptor == null)
            return false; // action does not exist so say yes - should we authorise this?!

        AuthorizationContext authContext = new AuthorizationContext(controllerContext);

        // run each auth filter until on fails
        // performance could be improved by some caching
        foreach (IAuthorizationFilter authFilter in actionDescriptor.GetFilters().AuthorizationFilters)
        {
            authFilter.OnAuthorization(authContext);

            if (authContext.Result != null)
                return false;
        }

        return true;
    }

    private static ControllerBase GetControllerByName(HtmlHelper helper, string controllerName)
    {
        // Instantiate the controller and call Execute
        IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();

        IController controller = factory.CreateController(helper.ViewContext.RequestContext, controllerName);

        if (controller == null)
        {
            throw new InvalidOperationException(

                String.Format(
                    CultureInfo.CurrentUICulture,
                    "Controller factory {0} controller {1} returned null",
                    factory.GetType(),
                    controllerName));

        }

        return (ControllerBase)controller;
    }

It could use some caching but for my case that was a premature optimization.


What is the problem you are trying to solve? It sounds like you may be headed down a path to a complex solution that could use a simple solution instead.

If a user doesn't have permissions to access the page after login, are you wanting non-logged in users to go to one page, while logged in users go to a different page?

If that's the case I might be tempted to create another controller for just such scenarios and redirect to that controller anywhere the user doesn't have access. Or if you are using your own base Controller I would put the functionality there.

Then the controller could present the desired view. For example if a non-logged in user tries to access a page they could get redirected to a generic error page. If the user is logged in, they could get redirected to a not authorized page.

This is very similar to Robert's answer.

Here's a basic skeleton for a base controller.

public BaseController: Controller
{

... // Some code

    public ActionResult DisplayErrorPage()
    {
        // Assumes you have a User object with a IsLoggedIn property
        if (User.IsLoggedIn())    
            return View("NotAuthorized");

        // Redirect user to login page
        return RedirectToAction("Logon", "Account");
    }

}

Then in lets say a AdminController (that inherits from BaseController) action

public ActionResult HighlyRestrictedAction()
{
    // Assumes there is a User object with a HasAccess property
    if (User.HasAccess("HighlyRestrictedAction") == false)
        return DisplayErrorPage();

    // At this point the user is logged in and has permissions
    ...
}


This is probably going to sound controversial, but I check security at the beginning of each controller method, inside the method:

public class ProductController : Controller
{
    IProductRepository _repository

    public ActionResult Details(int id)
    {
        if(!_repository.UserHasAccess(id))
            return View("NotAuthorized");

        var item = _repository.GetProduct(id);

        if (item == null)
            return View("NotFound");

        return View(item);
    }
}

The reason I don't use the [Authorize] attributes for this is that you cannot pass an id, or any other identifying information, to the attribute at runtime.


In my application I have created a custom filter derived from AuthorizeAttribute, so any unauthorized access will simply go to AccessDenied page. For links, I replace Html.ActionLink with a custom helper Html.SecureLink. In this helper extension, I check for this user's roles access to controller/action against database. If he/she have the authorization, return link otherwise return the link text with special remarks (could be image/ coloring/ js)


Why not attribute your controller methods with the security requirement.

I wrote an attribute to do this as follows:

  public class RequiresRoleAttribute : ActionFilterAttribute
        {
            public string Role { get; set; }

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                if (string.IsNullOrEmpty(Role))
                {
                    throw new InvalidOperationException("No role specified.");
                }


                if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    filterContext.HttpContext.Response.Redirect(loginUrl, true);
                }
                else
                {
                    bool isAuthorised = filterContext.HttpContext.User.IsInRole(this.Role);

                    << Complete Logic Here >>



                }  
            }      
        }


i just spent some time implementing @jfar's solution (updating it for non-deprecated GetFilters() version), and then i realized that i can skip this whole thing.

in my case (and i assume most cases) I have a custom AuthorizationAttribute to implement site authorization which in turn calls my authorization service to make the actual access level determinenation.

So in my html helper for generating menu links, i skipped right to the auth service:

@Html.MenuItem(@Url, "icon-whatever", "TargetController", "TargetAction")

public static MvcHtmlString MenuItem(this HtmlHelper htmlHelper, UrlHelper url,string iconCss, string targetController, string targetAction)
{
    var auth = IoC.Resolve<IClientAuthorizationService>().Authorize(targetController, targetAction);
    if (auth == AccessLevel.None)
        return MvcHtmlString.Create("");

*user is determined within the client auth service

public string GetUser() {
    return HttpContext.Current.User.Identity.Name;
}

*could also add some behavior for read-only access. it's nice because my auth service takes care of caching so i don't have to worry about performance.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号