How do you deal with authorisation on actions that return results other than ViewResult?

帅比萌擦擦* 提交于 2019-12-18 11:43:23

问题


I am using a custom authorization filter on my ASP.NET MVC controllers that redirects the user to a url other than the login screen if they fail authorisation on a particular action.

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

My current filter looks like this:

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

This indicates that if the user is not in the ServerAccess role then they should be redirected to /Home/Unauthorised/

I am curious how other people are handling this? This seems particularly problematic when you consider the number of actions that are intended to only be called by client-side script AJAX calls. How can the /Home/Unauthorised/ action know whether the caller was intended to receive a view, partialview, json, content, etc?


回答1:


I think you'll need to pass in that information with the redirection.

A couple ways you could handle this:

  • Consider making separate action methods for each type of response you need - UnauthorizedJson, UnauthorizedHtml, UnauthorizedEtc... that corresponded to the original action response type

  • Pass in the format information with the redirection by adding another parameter to the Unauthorized method and appending it to the URL in your filter




回答2:


Use Request.IsAjaxRequest(), e.g.:

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

Note 403, not 401, since ASP.NET intercepts 401s and turns them into HTML error pages. It doesn't matter what the AJAX call expected to receive; it can still see the status code.



来源:https://stackoverflow.com/questions/1472610/how-do-you-deal-with-authorisation-on-actions-that-return-results-other-than-vie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!