57

我正在使用 jquery 对 asp.net mvc 控制器操作进行 ajax 调用:

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetWeek(string startDay)
        {
            var daysOfWeek = CompanyUtility.GetWeek(User.Company.Id, startDay);
            return Json(daysOfWeek);
        }

当会话超时时,此调用将失败,因为用户对象存储在会话中。我创建了一个自定义授权属性,以检查会话是否丢失并重定向到登录页面。这适用于页面请求,但不适用于 ajax 请求,因为您无法从 ajax 请求重定向:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class AuthorizeUserAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.Request.IsAjaxRequest())
            {//validate http request.
                if (!httpContext.Request.IsAuthenticated
                    || httpContext.Session["User"] == null)
                {
                    FormsAuthentication.SignOut();
                    httpContext.Response.Redirect("~/?returnurl=" + httpContext.Request.Url.ToString());
                    return false;
                }
            }
            return true;
        }
    }

我在另一个线程上读到,当用户未通过身份验证并且您发出 ajax 请求时,您应该将状态代码设置为 401(未经授权),然后在 js 中检查并将它们重定向到登录页面。但是,我无法正常工作:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (Request.IsAjaxRequest() && (!Request.IsAuthenticated || User == null))
            {
                filterContext.RequestContext.HttpContext.Response.StatusCode = 401;
            }
            else
            {
                base.OnActionExecuting(filterContext);
            }
        }

基本上,它会将其设置为 401,但随后它将继续进入控制器操作并抛出未设置为对象错误实例的对象引用,然后将错误 500 返回给客户端 js。如果我更改我的自定义 Authorize 属性以验证 ajax 请求并为那些未通过身份验证的请求返回 false,这会使 ajax 请求返回我的登录页面,这显然不起作用。

我如何让这个工作?

4

8 回答 8

86

您可以编写一个自定义[Authorize]属性,该属性将返回 JSON 而不是在未经授权的访问情况下引发 401 异常,这将允许客户端脚本优雅地处理该场景:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.Result = new JsonResult
            {
                Data = new 
                { 
                    // put whatever data you want which will be sent
                    // to the client
                    message = "sorry, but you were logged out" 
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

然后用它和客户端装饰你的控制器/动作:

$.get('@Url.Action("SomeAction")', function (result) {
    if (result.message) {
        alert(result.message);
    } else {
        // do whatever you were doing before with the results
    }
});
于 2011-03-09T07:43:38.940 回答
38

我不会将 JsonRequestBehavior 更改为 AllowGet。相反,我建议:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class MyAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
        OnAuthorizationHelp(filterContext);
    }

    internal void OnAuthorizationHelp(AuthorizationContext filterContext)
    {

        if (filterContext.Result is HttpUnauthorizedResult)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.StatusCode = 401;
                filterContext.HttpContext.Response.End();
            }
        }
    }
}

并添加全局 js ajax 错误处理程序:

   $(document).ajaxError(function (xhr, props) {
        if (props.status === 401) {
            location.reload(); 
        }
   }
于 2012-06-02T22:14:42.277 回答
10

即使这是过去的答案,我认为如果您使用的是 .NET 4.5,这是最短和最甜蜜的答案。添加了名为 SuppressFormsAuthenticationRedirect 的小属性。设置为 true 并且它不会执行 302 重定向到登录页面。

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.suppressformsauthenticationredirect.aspx

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        // returns a 401 already
        base.HandleUnauthorizedRequest(filterContext);
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            // we simply have to tell mvc not to redirect to login page
            filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
        }
    }
}

假设您计划处理 ajax 请求失败/错误回调,您将在其中获得 401 Unauthorized。

于 2013-05-11T02:22:34.907 回答
7

在母版页上添加这个 jquery 脚本 ------------

<script type="text/javascript">

   $.ajaxSetup({
        statusCode: {
            403: function () {
                window.location.reload();
            }
        }
    });


    OR


    $.ajaxSetup({
        error: function (x, e) {
            if (x.status == 403) {
                window.location.reload(); 
            }
        }
    });

</script>

在你的项目中添加一个名为 TraceFilter 的 cs 文件,并编写一个继承到 ActionFilterAttribute 的密封类 TraceFilterAttribute。通过写入以下行,在您项目的 App_Start 文件夹中可用的 FilterConfig.cs 中添加 TraceFilterAttribute 类。

filters.Add(new TraceFilterAttribute());

覆盖 TraceFilterAttribute 类中的 OnActionExecuting() 方法。这将自动检查会话,如果发现会话为空,则调用母版页中可用的脚本,您可以从它们转到您的选择页面。

[AttributeUsage(AttributeTargets.All)]
public sealed class TraceFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext != null)
        {
HttpSessionStateBase objHttpSessionStateBase = filterContext.HttpContext.Session;
                var userSession = objHttpSessionStateBase["etenetID"];
if (((userSession == null) && (!objHttpSessionStateBase.IsNewSession)) || (objHttpSessionStateBase.IsNewSession))
                {
                    objHttpSessionStateBase.RemoveAll();
                    objHttpSessionStateBase.Clear();
                    objHttpSessionStateBase.Abandon();
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        filterContext.HttpContext.Response.StatusCode = 403;
                        filterContext.Result = new JsonResult { Data = "LogOut" };
                    }
                    else
                    {
                        filterContext.Result = new RedirectResult("~/Admin/GoToLogin");
                    }

                }


}
}

}
于 2013-07-01T11:46:14.557 回答
4

我遇到了类似的问题,发现了这个

在返回响应之前,强制 ASP.NET 返回 401 代码,而不是返回任何 JSON。在Global.asax

protected void Application_EndRequest()
    {
        var context = new HttpContextWrapper(Context);
        if (context.Request.IsAjaxRequest() && context.Response.StatusCode == 302)
        {
            Context.Response.Clear();
            Context.Response.Write("**custom error message**");
            Context.Response.StatusCode = 401;
        }
    }

然后你可以让客户端用 JavaScript/jQuery 或你正在使用的任何东西来处理它

于 2012-12-15T18:37:36.753 回答
1

这是我在自定义授权中以如此简单的方式处理此问题的方法,我检查会话是否已结束并使用布尔值将其处理为未经授权,以检查它是否确实经过身份验证但未经授权(重定向到未经授权的页面)或者由于会话超时而未通过身份验证(重定向到登录)

 private bool ispha_LoggedIn = false;
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        ispha_LoggedIn = false;
        var session = httpContext.Session;
        bool authorize = false;
        if (httpContext.Session["authenticationInfo"] == null)
        {

            return authorize;
        }

        using (OrchtechHR_MVCEntities db = new OrchtechHR_MVCEntities())
        {
            UserAuthenticationController UM = new UserAuthenticationController();
            foreach (var roles in userAssignedRoles)
            {
                authorize = UM.IsUserInRole(httpContext.User.Identity.Name, roles);

                if (authorize)
                {

                    return authorize;
                }

            }
        }
        ispha_LoggedIn = true;
        return authorize;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (ispha_LoggedIn==false)
        {
            filterContext.Result = new RedirectResult("~/UserAuthentication/LogIn");
        }
        else
        {
            filterContext.Result = new RedirectResult("~/Dashboard/UnAuthorized");
        }


    }

希望这能指导某人,如果有评论,请尽管了解他们。

于 2016-05-07T14:55:58.857 回答
0

您可能想尝试抛出 HttpException 并在您的 javascript 中捕获它。

throw new HttpException(401, "Auth Failed")
于 2011-03-08T22:11:32.500 回答
-3

如果会话过期,则在 ajax 调用中返回类似这样的内容

<script>
$(function(){
    location.reload();
});
</script>

哈哈...

于 2016-03-31T16:07:45.617 回答