无法在 ajax 中处理 302 重定向,为什么? [英] Cannot handle 302 redirect in ajax and why?

查看:14
本文介绍了无法在 ajax 中处理 302 重定向,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用表单身份验证用 asp.net mvc 编写的后端服务器.当用户未通过身份验证时,服务器会自动发送 302 重定向到登录操作并返回登录页面.

I have a back-end server written in asp.net mvc using Forms Authentication. When the user is not authenticated, the server will automatically send a 302 redirect to a Login action and return a Login page.

在客户端,我有一个项目列表.此列表仅供经过身份验证的用户访问.在页面上,我有一个使用 Ajax(jQuery 的 $.ajax 函数)刷新列表的按钮.

On client side, I have a list of items. This list is only accessible to authenticated users. On the page, I have a button to Refresh the list using Ajax ($.ajax function of jQuery).

现在,我的问题是当身份验证票超时并且用户单击刷新按钮时:

Now, my problem is when the authentication ticket is timeout and the user clicks on the Refresh button:

  • 我的函数发送一个 ajax 请求来获取刷新的列表
  • 服务器检测到身份验证票证无效并发出 302 重定向.
  • 浏览器自动处理该 302 响应并强制我的 ajax 函数向 Login 操作发送另一个 ajax 请求,最终结果是状态为 200 的 HTML.我的脚本很混乱,因为列表是也是一个状态为 200 的 HTML.
  • My function sends an ajax request to get the refreshed list
  • The server detects that the authentication ticket is not valid and issues a 302 redirect.
  • The browser automatically handles that 302 response and forces my ajax function to send another ajax request to the Login action and the final result is an HTML with status 200. My script is confused because the list is also an HTML with status 200.

我想要的是当身份验证票超时并且用户单击刷新按钮时,我应该能够检测到并显示一条消息要求用户登录.

What I want is when the authentication ticket is timeout and the user clicks on the Refresh button, I should be able to detect that and display a message asking the user to Login.

我尝试通过在登录操作中添加自定义标头 (IS_LOGIN) 并在我的 ajax 响应中检查它来解决此问题.但这不是一个好的解决方案.

I tried to workaround this by adding a custom header (IS_LOGIN) in the Login action and check that in my ajax response. But it is not a good solution.

所以我的问题是:

  • 解决此问题的最佳方法是什么?
  • 为什么浏览器不让我们的脚本处理 302 响应?并且只是自动强制我们的 ajax 创建另一个请求.这是浏览器或jquery库的问题?这有什么原因吗?(安全,...)

感谢您的任何回复.

推荐答案

当调用是 XHR 时,不应重定向调用,而是使用 401 Unauthorized 响应并在回调中处理此问题.我不知道 ASP.NET,但我对 Spring Security 做了类似的事情.

You shouldn't redirect the call when it's an XHR but respond with a 401 Unauthorized and handle this in your callbacks. I don't know ASP.NET but I did something similar with Spring Security.

概念如下:

  • 获取认证状态
  • 检查 X-Requested-With: XMLHttpRequest
  • 的标头
  • 找到且未通过身份验证时,使用 401 Unauthorized
  • 响应
  • 未找到且未经过身份验证的重定向.

底线是,在某些情况下,XHR 调用需要与其他 HTTP 请求不同的处理方式.如果相同的资源位于另一个位置,您应该只重定向 XHR.

The bottom line is that XHR calls need to be handled differently then other HTTP requests in some cases. You should only redirect a XHR if the same resource is at another location.

您无法使用 XHR 回调处理重定向,因为浏览器会自动处理它们.您只会取回重定向位置的内容.

You can't handle redirects with XHR callbacks because the browser takes care of them automatically. You will only get back what at the redirected location.

这篇关于无法在 ajax 中处理 302 重定向,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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