如何将自定义AuthorizeAttribute与AJAX一起使用

How to use custom AuthorizeAttribute with AJAX

本文关键字:AJAX 一起 AuthorizeAttribute 自定义      更新时间:2023-09-26

在其他朋友的帮助下,我设法从这个主题中找到了解决问题的方法:允许一个帐户一次由一个人使用的可重用方法

我有一个SingleLogin类,它继承了AuthorizeAttribute,并实现了一个自定义AuthorizeCore方法,用于重新使用我的单一登录代码:

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool isAuthorized = base.AuthorizeCore(httpContext);
        if (isAuthorized)
        {
            int userId = (int)WebSecurity.CurrentUserId;
            using (var db = new UsersContext())
            {
                if ((httpContext.Session.SessionID != db.getSessionId(userId))
                    || db.getSessionId(userId) == null)
                {
                    WebSecurity.Logout();
                    isAuthorized = false;
                    httpContext.Response.Redirect("/Home/Index");
                }
            }
        }
        return isAuthorized;
    }

除了我的JsonResult操作之外,一切都很好:

    [HttpPost]
    public JsonResult MessageSave(string message)
    {
        bool messageSaved = false;
        int userId = (int)WebSecurity.CurrentUserId;
        message = HttpUtility.HtmlEncode(message);
        // Model method - adding chat log - db
        db.addChatLog(message, userId);
        messageSaved = true;
        return Json(new { messageSaved = messageSaved });
    }

这个方法是由Ajax POST调用触发的,您可以在下面的代码示例中看到。只是基本的POST。

编辑3请检查这些图像:https://i.stack.imgur.com/x3L5E.jpg。。嗯,我想POST确实触发了,但不知道为什么当我尝试在$.ajax之前测试它时,我的警报不起作用…正如你在响应中看到的,我确实得到了主页/索引页面,但我没有立即重定向到主页/索引(文本留在textBox中,页面只是等待…),我必须再次按下回车键才能重定向。。很奇怪。

编辑2似乎我甚至在注销后都无法访问我的jQuery。我在.js文件中放了一些警告。

我有一个单独的.js文件,然后作为<script src="~/Scripts/custom/homeChat.js"></script>放在我的视图中。我通过HTML5数据将View中的Razor值传递到我的JS文件中。

我的textBox元素#txtMsg触发了我的jQuery事件,因此当我注销时,它可能不再识别我的textBox元素,也不会触发我的jQuery事件?

在视图中触发.js的元素是:@Html.TextBox("txtMsg")

JS:

$("#txtMsg").keypress(function (e) {
        //when enter
        if (e.which == 13) {
            alert("ALERT DOESNT TRIGGER");
                $.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify({ message: input }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if (data.messageSaved) {
                            $("#txtMsg").val("");
                        }
                        else {
                            window.location.href = urlhome;
                        }
                    }
                });
            }
        }
    });

所以,如果你甚至不能参加你的活动,你怎么能知道出了什么问题?我有这个˙HandleUnauthorizedRequest,但如果我理解正确的话,你必须进入你的jQuery事件(在我的例子中是上面js代码中的.keypress)才能工作。

编辑:附加说明

所以让我来解释一下这个场景。如果我在Firefox中使用用户名"john"登录,在chrome中再次使用用户名"john"登录,我在Firefox的下一步操作将使我注销并重定向到Home/Index,因为其他人在chrome中进行了新登录。

没关系。由于您不再登录,如果您的操作是正常的ActionResult并返回视图,则会正常重定向到您的Home/Index。

我遇到的问题是,我在页面中有一些其他功能,它使用Ajax POST,由于您已注销,您无法POST到JsonResult操作,因此您甚至无法接收到错误回调,该回调会将您重定向到Home/Index。我在JS中放入了一些警报,但没有警报触发,这是正常的,因为无论如何我都不允许再出现在那个页面上。如果我想让onEnter文本框将我重定向到主页/索引,我必须按enter键两次。能做的就这些吗?

我对解决AJAX问题的最佳方法感兴趣。我不知道该怎么称呼它,但正如我从上一个主题中读到的,它被称为"处理AJAX超时"?

非常感谢。

您可以通过处理AJAX请求中的错误

$.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify({ message: input }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        if (data.messageSaved) {
            $("#txtMsg").val("");
        }
        else {
            window.location.href = urlhome;
        }
    },
    error: function(xhr, status, error) {
        // TODO: may be check error or status or xhr.statusCode()
        window.location.href = urlhome;
    }
});

jQuery $.ajax()文档

如果理解正确,您希望处理未经授权的ajax请求

在这种情况下,您可以覆盖属性中的HandleUnauthorizedRequest方法:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    if (filterContext.HttpContext.Request.IsAjaxRequest()) 
    {
        filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
        filterContext.Result = new JsonResult();
    }
    else
    {
        filterContext.Result = new HttpStatusCodeResult((int)HttpStatusCode.Forbidden);
    }
}