How do you feel about authorization in actions that return results other than ViewResult?

I use a custom authorization filter on my ASP.NET MVC controllers, which redirects the user to a URL other than the login screen if they are not authorized for a specific action.

This is fine for actions that return views, but many of my actions return other types of results, such as PartialResult or JsonResult.

My current filter is as follows:

<AuthorizeWithRedirect (Roles: = "ServerAccess", Controller: = "Home", Action: = "Unauthorized")>

This means that if the user is not in the ServerAccess role, they should be redirected to / Home / Unauthorized /

I'm curious how other people handle this? This seems especially problematic if you are considering the number of actions that are intended to be invoked only on the client side by an AJAX script. How can / Home / Unauthorized / action know if the caller should receive a view, partial view, json, content, etc.

+5
source share
2 answers

I think you will need to pass this information with a redirect.

A few ways to handle this:

  • Consider creating separate action methods for each type of response you need - UnauthorizedJson, UnauthorizedHtml, UnauthorizedEtc ..., which corresponds to the original type of response to the action

  • , URL- .

+1

Request.IsAjaxRequest(), :

public sealed class AjaxAuthorizeAttribute : AuthorizeAttribute
{
    public AjaxAuthorizeAttribute() : base()
    {
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // Extends the original Web.MVC.AuthorizeAttribute for Ajax calls.
        // Basically if the request is not authorized and the request is an AJAX Request.
        // then we simply set the stats Code to 403 and set an empty Result, in order to 
        // determine in Javascript if the AJAX call came back completed and valid.
        base.OnAuthorization(filterContext);
        if (filterContext.Result == null)
        {
            return;
        }
        else if (filterContext.Result.GetType() == typeof(HttpUnauthorizedResult) 
                 && filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.Result = new ContentResult();
            filterContext.HttpContext.Response.StatusCode = 403;
        }
    }
}

403, 401, ASP.NET 401s HTML. , AJAX-; .

+9

All Articles