小编典典

未验证用户身份时如何处理ajax请求?

ajax

未验证用户身份时如何处理ajax请求?

有人进入页面,留出一个小时的空间,返回,然后使用jQuery($.post)在通过ajax的页面上添加评论。由于未通过身份验证,因此方法返回RedirectToRoute结果(重定向到登录页面)。你用它做什么?您如何在客户端处理它,以及如何在控制器中处理它?


阅读 247

收藏
2020-07-26

共1个答案

小编典典

编辑:

我很久以前就写了以上答案,现在我认为发送403不是正确的方法。403的含义略有不同,因此不应使用。这是使用401纠正的属性。只有context.HttpContext.Response.End()Http401Result中的其他属性和不同的HTTP代码不同:

public class OptionalAuthorizeAttribute : AuthorizeAttribute
{
    private class Http401Result : ActionResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            // Set the response code to 401.
            context.HttpContext.Response.StatusCode = 401;
            context.HttpContext.Response.Write(CTRes.AuthorizationLostPleaseLogOutAndLogInAgainToContinue);
            context.HttpContext.Response.End();
        }
    }

    private readonly bool _authorize;

    public OptionalAuthorizeAttribute()
    {
        _authorize = true;
    }

    //OptionalAuthorize is turned on on base controller class, so it has to be turned off on some controller. 
    //That is why parameter is introduced.
    public OptionalAuthorizeAttribute(bool authorize)
    {
        _authorize = authorize;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //When authorize parameter is set to false, not authorization should be performed.
        if (!_authorize)
            return true;

        var result = base.AuthorizeCore(httpContext);

        return result;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            //Ajax request doesn't return to login page, it just returns 401 error.
            filterContext.Result = new Http401Result();
        }
        else
            base.HandleUnauthorizedRequest(filterContext);
    }
}

老答案:

虽然我喜欢其他答案中发布的想法(我以前有一个想法),但我需要代码示例。他们来了:

修改的授权属性:

public class OptionalAuthorizeAttribute : AuthorizeAttribute
{
    private class Http403Result : ActionResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            // Set the response code to 403.
            context.HttpContext.Response.StatusCode = 403;
            context.HttpContext.Response.Write(CTRes.AuthorizationLostPleaseLogOutAndLogInAgainToContinue);
        }
    }

    private readonly bool _authorize;

    public OptionalAuthorizeAttribute()
    {
        _authorize = true;
    }

    //OptionalAuthorize is turned on on base controller class, so it has to be turned off on some controller. 
    //That is why parameter is introduced.
    public OptionalAuthorizeAttribute(bool authorize)
    {
        _authorize = authorize;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //When authorize parameter is set to false, not authorization should be performed.
        if (!_authorize)
            return true;

        var result = base.AuthorizeCore(httpContext);

        return result;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            //Ajax request doesn't return to login page, it just returns 403 error.
            filterContext.Result = new Http403Result();
        }
        else
            base.HandleUnauthorizedRequest(filterContext);
    }
}

HandleUnauthorizedRequest被覆盖,因此Http403Result在使用Ajax时返回。Http403Result将StatusCode更改为403,并作为响应将消息返回给用户。属性(authorize参数)中还有一些附加逻辑,因为我[Authorize]在基本控制器中打开了该功能,并在某些页面中将其禁用了。

另一个重要部分是在客户端全局处理此响应。这是我放在Site.Master中的内容:

<script type="text/javascript">
    $(document).ready(
        function() {
            $("body").ajaxError(
                function(e,request) {
                    if (request.status == 403) {
                        alert(request.responseText);
                        window.location = '/Logout';
                    }
                }
            );
        }
    );
</script>

我放置了一个GLOBAL
ajax错误处理程序$.post,一旦失败并出现403错误,就会警告响应消息,并将用户重定向到注销页面。现在,我不必处理每个$.post请求中的错误,因为它是全局处理的。

为什么是403,而不是401?401由MVC框架在内部处理(这就是为什么在授权失败后重定向到登录页面的原因)。

你怎么看待这件事?

2020-07-26