views:

1065

answers:

2

I am writing an application where by someone can edit paragraphs on a web page. jQuery is used to send and receive the edited paragraph data to a handler, which saves it or reads it from a database. The problem is that if the forms authentication has timed out, I get the login page back from my handler. Is there any way I can detect at the client or server if the authentication has timed out and redirect the entire page to the login page?

+1  A: 

In my application, on the client side, I check the HTTP status of the returned page. If it is 401(Unauthorized Error), I present the login form in a modal dialog. You could re-authenticate like that or just redirect using

window.location = 'http://someurl.com';

This requires cooperation of the server to return a 401, but this seems like the cleanest way to me.

Ben
That sounds good, but how do I get my app to return 401 rather than 200 and the login page?
Sprintstar
See my answer for why I think you can't.
Crescent Fresh
See my answer for why it's possible in the recent .NET 3.5.
Peter J
+1  A: 

I recently accomplished a method for handling 401s which I think will work for you as well. The problem in past versions of .NET is that error pages wouldn't return the proper error code, they just 302 to the specified page.

With .NET 3.5, your error handler can "rewrite" instead of "redirect" using redirectMode:

<customErrors mode="On" defaultRedirect="/err.aspx" redirectMode="ResponseRewrite">
  <error statusCode="404" redirect="/404.aspx"/>
</customErrors>

Since all requests (including web service calls) will now return the proper HTTP status code, you can properly use the 404 / 401 / 500 code in your javascript.

Then, in your client code (this is in jQuery and is redirecting on any errors, not only 401s, but you get the idea):

$(document).ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError) {
  window.location.href('/error.aspx');
});
Peter J
This doesn't appear to be changing the way forms authentication redirects work for me. Have you tried this?
StriplingWarrior
Yes, it is running as described here. Note that it requires the application to be running against .NET 3.5. It won't work in 2.0.
Peter J