如何处理返回ViewResult以外的结果的操作的授权?

Nic*_*ick 5 ajax asp.net-mvc json authorization

我在我的ASP.NET MVC控制器上使用自定义授权过滤器,如果用户在特定操作上失败,则会将用户重定向到登录屏幕以外的URL.

这对于返回视图的操作是可以的,但是我的许多操作都返回其他结果类型,例如PartialResult或JsonResult.

我当前的过滤器如下所示:

<AuthorizeWithRedirect(角色:="ServerAccess",控制器:="主页",操作:="未经授权")>

这表示如果用户不在ServerAccess角色中,则应将其重定向到/ Home/Unauthorized /

我很好奇其他人是如何处理这个的?当您考虑仅由客户端脚本AJAX调用调用的操作数时,这似乎特别成问题./ Home/Unauthorized/action如何知道调用者是否打算接收视图,部分视图,json,内容等?

Cra*_*ntz 9

使用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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意403,而不是401,因为ASP.NET拦截401s并将它们转换为HTML错误页面.AJAX呼叫期望接收什么并不重要; 它仍然可以看到状态代码.


wom*_*omp 1

我认为您需要通过重定向传递该信息。

有几种方法可以解决这个问题:

  • 考虑为您需要的每种类型的响应创建单独的操作方法 - UnauthorizedJson、UnauthorizedHtml、UnauthorizedEtc...与原始操作响应类型相对应

  • 通过向 Unauthorized 方法添加另一个参数并将其附加到过滤器中的 URL,通过重定向传递格式信息