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

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

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘