Authorize attribute and jquery AJAX in asp.net MVC

2020-01-24 03:59发布

I have used jquery ajax function to submit a form. The users have to be logged in else they must redirect to a login page.I have used Authorize() attribute for it.

[Authorize]
public ActionResult Creat()
{
....
}

If the user is not login the action return login page to jquery's ajax functions and it is displayed on the same page but I want to redirect the user to login page. Is there any solution?

3条回答
来,给爷笑一个
2楼-- · 2020-01-24 04:33

As another extension to Ronnie Overby's answer.

His solution doesn't work with webapi, but this is fine because you can use normal Authorize attribute instead and then handle the 401 status in the ajaxError function as follows.

    $(document).ajaxError(function (e, xhr) {
    //ajax error event handler that looks for either a 401 (regular authorized) or 403 (AjaxAuthorized custom actionfilter). 
    if (xhr.status == 403 ||xhr.status == 401) {
       //code here
    }
});
查看更多
干净又极端
3楼-- · 2020-01-24 04:34

Just a handy addition to #Ronnie's answer

if you want to keep the page url on redirect.

 var pathname = window.location.pathname;
        if (xhr.status == 403) {
                var response = $.parseJSON(xhr.responseText);
                window.location = response.LogOnUrl + '?ReturnUrl=' + pathname;
            }
查看更多
手持菜刀,她持情操
4楼-- · 2020-01-24 04:51

Working example: https://github.com/ronnieoverby/mvc-ajax-auth

Important parts:

AjaxAuthorizeAttribute:

using System.Web.Mvc;

namespace MvcApplication1
{
    public class AjaxAuthorizeAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext context)
        {
            if (context.HttpContext.Request.IsAjaxRequest())
            {
                var urlHelper = new UrlHelper(context.RequestContext);
                context.HttpContext.Response.StatusCode = 403;
                context.Result = new JsonResult
                {
                    Data = new
                    {
                        Error = "NotAuthorized",
                        LogOnUrl = urlHelper.Action("LogOn", "Account")
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                base.HandleUnauthorizedRequest(context);
            }
        }
    }
}

Javascript:

    $(function () {
        $(document).ajaxError(function (e, xhr) {
            if (xhr.status == 403) {
                var response = $.parseJSON(xhr.responseText);
                window.location = response.LogOnUrl;
            }
        });
    });

Use the attribute in a controller:

    [AjaxAuthorize]
    public ActionResult Secret()
    {
        return PartialView();
    }

Do some ajax:

@Ajax.ActionLink("Get Secret", "Secret", new AjaxOptions { UpdateTargetId = "secretArea", })

<div id="secretArea"></div>
查看更多
登录 后发表回答