weixin_33736649 2016-12-27 19:04 采纳率: 0%
浏览 67

Ajax授权失败

I am building MVC web application that for at least part of its data transfer relies on Ajax.

The controller action is

[RBAC]
[Authorize]
public string GetData(string inputdata)
{
   some code ...
   return jsondata;
}

The ajax call is

 $.ajax({
       dataType: "json",
       url: Url,
       data: { '_inputdata': selectedText },
       success: function (data)
       {
           response($.map(data,
              function(item, index) {
              return {
                   label: item.label,
                   value: item.value
               }
            }));
       },
      error: (function (jqXHR, textStatus, errorThrown, data) {
           ProcessFail(jqXHR, textStatus, errorThrown,  data);
        });
      })
  }); 

[RBAC] causes an authorization check to be done which is what I want.

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
      ......
         filterContext.Result = new RedirectToRouteResult
              (new RouteValueDictionary { { "action", "Index" }, 
              { "controller", "Unauthorised" } , 
              { "Area", String.Empty }});
       .....
    } 

The problem is that I don't get anything back at the ajax except a failure. There is nothing that tells me that there was an authorization error.

Questions:

  1. Is it possible to get back information from an authorization failure into the ajax response. If so how?
  2. If the answer to 1. is no, should I be checking for this authorization before I make this call?

As always, any help appreciated.

  • 写回答

3条回答 默认 最新

  • weixin_33713350 2016-12-27 19:51
    关注

    Looks like you are using MVC rather than Web API, Web API should give you a nice JSON message by default.

    One option would be to check the status code of the response, this should give you a 401 if it is an authentication failure.

    Another would be to remove the [Authorize] and do a check inside of the method itself

    public string GetData(string inputdata)
    {
       if (User.Identity.IsAuthenticated) { 
          return  jsonData;
       } 
       return failureJson;
    }
    

    Note: I am sure there is a fancier way to do this but this should work

    评论

报告相同问题?