54

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.

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:

  • 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.

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.

So my questions are:

  • What is the best way to deal with this problem?
  • Why does the browser not let our script handle 302 response? and just automatically forces our ajax to create another request. This is a problem with the browser or jquery library? Any reasons for this? (security,...)

Thanks for any replies.

4

1 に答える 1

46

XHR の場合は呼び出しをリダイレクトするべきではありませんが、a で応答し、401 Unauthorizedコールバックでこれを処理してください。ASP.NET はわかりませんが、Spring Security で同様のことを行いました。

コンセプトは次のとおりです。

  • 認証状態を取得する
  • ヘッダーを確認してくださいX-Requested-With: XMLHttpRequest
  • 見つかったが認証されていない場合は、次のように応答します401 Unauthorized
  • 見つからず、認証されていない場合はリダイレクトします。

肝心なのは、場合によっては、XHR 呼び出しを他の HTTP 要求とは異なる方法で処理する必要があるということです。同じリソースが別の場所にある場合にのみ、XHR をリダイレクトする必要があります。

あなたの質問に答えるために

ブラウザが自動的にリダイレクトを処理するため、XHR コールバックでリダイレクトを処理することはできません。リダイレクトされた場所にあるものだけが返されます。

于 2013-04-14T08:03:31.803 に答える