不同的反应,非认证用户和AJAX调用 [英] Different response to non-authenticated users and AJAX calls

查看:154
本文介绍了不同的反应,非认证用户和AJAX调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的ASP MVC(1.0)的网站有一个默认的登录页面(基于OpenID的 - 但这不应该做出不同的)。它正常工作时AuthorizedAttribute是在动作/控制器。

My ASP MVC (1.0) website has a default login page (based on OpenId - but that shouldn't make a different). It works fine when AuthorizedAttribute is on the Action/Controller.

不过,我有AJAX请求进来的为好。以下是我与他们无关:

However, I have AJAX requests coming in as well. Here is what I do with them:

if (Request.IsAjaxRequest())
{ 
  if (Request.IsAuthenticated)
  {
    // Authenticated Ajax request
  }
  else
  {
    // Non-authenticated Ajax request.
    Response.StatusCode = (int)HttpStatusCode.Unauthorized;
    return Json(new { response = "AUTHENTICATION_FAILED" });
   }
}

现在的问题是,如果我设置Response.Status code未经授权,请求重定向到我的登录页这是不好的Ajax请求。

The problem is if I set the Response.StatusCode to Unauthorized, the request is redirected to my login page which is not good for Ajax requests.

对于这个问题有什么建议是AP preciated。

Any suggestions for this issue is appreciated.

推荐答案

这是一个常见的​​问题。

This is a common problem.

该授权属性返回一个HTTP 401未经授权的响应。然而遗憾的是,如果你有FormsAuthentication启用,401是由FormsAuthenticationModule,然后执行一个重定向到登录页面拦截 - 然后返回一个HTTP 200(登录页)回到您的Ajax请求

The Authorize attribute returns a Http 401 Unauthorized response. Unfortunately, however if you have FormsAuthentication enabled, the 401 is intercepted by the FormsAuthenticationModule which then performs a redirect to the login page - which then returns a Http 200 (and the login page) back to your ajax request.

最好的办法是修改自己的认证code返回不同的HTTP状态code - 说403 - 未捕获的formsAuthenticationModule,你可以在你的Ajax方法捉

The best alternative is to modify your authorization code to return a different Http status code - say 403 - which is not caught by the formsAuthenticationModule and you can catch in your Ajax method.

这篇关于不同的反应,非认证用户和AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆