Simple way to monitor result of request to detect session timeout? - javascript

I've got an Ajax app I would like to add sessions and logins to.
Currently the app uses jQuery get shorthand to send a request
that.ajaxRequest = $.get(query_string, function(data, textStatus, xhr) {
// do somthing with data
});
I have a system on the server that throws an error message if the session has expired.
On the client I know I can deal with this using the following:
that.ajaxRequest = $.get(query_string, function(data, textStatus, xhr) {
if (data == "E_TIMEOUT") {
// redirect to login
} else {
// do something
}
});
However I would prefer not to have to write the same timeout code for every $.get - there are a bunch of them throughout the app.
Is there a way to monitor the result of a request and take action if necessary, without rewriting all of my $.get statements?
Thanks,

You can use $.ajaxSetup() for this:
$.ajaxSetup({
complete: function (xhr) {
if (xhr.getResponseHeader('E_TIMEOUT') == "1") {
//redirect to login
}
}
});
This approach is slightly different, it uses response headers which you can get without parsing data an extra time every request (that is possible, though not documented and subject to break), which you would have to do otherwise, in a global situation.
On the server-side where you're sending E_TIMEOUT for the response, just change it to add a header as well, E_TIMEOUT=1 (or whatever header you want). I actually put this header on my login page only, the timeouts redirect via a 302 (which XmlHttpRequest transparently follows), so if the user timeouts and the AJAX request actually ended up at the login page, I do a location.reload() to reflect this on the page. That's just another option if you go that route, it looks like this:
$.ajaxSetup({
complete: function (xhr) {
if (xhr.getResponseHeader('LoginPage') == "1") {
location.reload();
}
}
});
Without knowing what server platform you're using I can't say how to set headers, but it's pretty easy on every common platform.

You should use firefox and download a program called 'FireBug'. This will show you all the requests being sent out, and the response that comes back from the AJAX call. It is action packed with goodness & web dev tools.

Related

AJAX event for when the server receives the request - before processing it

I'm currently developing a class in PHP that makes cURL requests and returns the answer as JSON for it to be processed by jQuery on my page. So far — no problems.
(Note that the only way for me to load that content is by using my own server - I'm querying a website's API with my private API key)
The problem is that some pages are slow (because of their server), and that plus the request to my server with jQuery makes it long to load a page, which makes around 5 seconds (or more) with no feedback at all for the user.
What I was wondering if there's any jQuery event for $.ajax which is called when the request is sent to the server (meaning that the server also started loading the requested page), but before the actual request to my page ended.
I'm trying to achieve this:
*user click* (0)
Sending request... (1)
Request sent. Loading page... (2)
Page loaded. (2)
Event 0 would be just a click
Event 1 would be jQuery's $.ajax({ beforeSend: function(){} );
Event 2 is what I want. It'd be something like onSend, but sadly it doesn't exist
Event 3 would be jQuery's $.ajax({ complete: function(){ } });
As a side note: I'm using jQuery, but I have no problems in using plain JavaScript if needed.
Maybe something like this can perform what you want:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 2) {
alert("loading page");
}
}
XMLHttpRequest has this states:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
I don't know if this really works. I never had to use a differente state of 4.
The Ajax have the default events that can be handled with here on the reference: http://api.jquery.com/jquery.ajax/
But i'll do a sample to you see how it works.
The HTML code for a sample:
<input type=button id=yourButtonID name=yourButtonID>
-> (0) - The onClick event.
$("#yourButtonID").click(AjaxFunction());
-> (1), (2), (3) The AjaxFunction.
function AjaxFunction(){
$.ajax({
url: "http://www.stackoverflow.com"
}).beforeSend(function() {
//show the ajax image
}).done(function(data) {
alert(data);
}).fail(function() {
alert("sorry, it failed");
}).success(function() {
alert("Sucess!");
});
}
If you want to show to the user that the Request is happening, you just need to show to the user a ajax loading image on the beforeSend event, like that one:
Something like onSend is the beforeSend because it executes before sending, and while are you sending, why you would fire a event?
Basically, ajax is a useful tool to make XHR's (XMLHTTPRequest's) that have pre-made events that you can use before you send the request, when your request is done, and if it fails, and if it success.
Basically, you want two responses from server: the first as soon as it receives your request, and the second containing the payload from the other server.
Since a regular ajax HTTP request can only have one response, you could use web sockets instead.
This allows the server to 'push' data to the client.
see the links below:
https://developer.mozilla.org/en-US/docs/WebSockets
http://www.html5rocks.com/en/tutorials/eventsource/basics/

How to handle specific HTTP error for all AJAX calls?

I have a web app, requesting and sending data via AJAX, and as a response, my server-side sends HTTP status codes, depending on the situation. so for example if a user tries to login while he's logged I probably return a 400 HTTP status code. And eventually i handle it with an alert, etc.
But handling these HTTP Status codes gets too heavy, since I'm making heavy use of AJAX. that means I'll be handling HTTP status code repeatedly with every AJAX request, which will result in duplicated code, and that's a bad practice.
So, what I'm looking for is a way to handle all these errors in one place, so I just handle all 400, 401, etc with the same code.
What i'm currently doing:
Handling the errors manually for each AJAX call. By using the statusCode in$.ajax().
statusCode: {
500: function(data) {
alert('Some friendly error message goes here.');
}
It seems like an overkill for me, as my web app develops, and as I create more ajax calls. I'll be repeating this piece of code again and again.
Currently, the only idea I have in mind is creating a function that will work on top of AJAX, something like:
function doAjax(type,url, data, moreVars) {
//this function is just a SIMPLE example, could be more complex and flexible.
$.ajax({
type: type,
url: url,
data: data,
moreOptions:moreVars,
//now handling all status code.
statusCode: {
//handle all HTTP errors from one place.
}
});
}
doAjax("POST", 'mydomain.com/login.php', dataObj);
You can use $.ajaxSetup() to register global error state handlers.
Description: Set default values for future Ajax requests.
Example:
$.ajaxSetup({
statusCode: {
500: function(data) {
alert('Some friendly error message goes here.');
}
}
});

AD FS 2.0 Authentication and AJAX

I have a web site that is trying to call an MVC controller action on another web site. These sites are both setup as relying party trusts in AD FS 2.0. Everything authenticates and works fine when opening pages in the browser window between the two sites. However, when trying to call a controller action from JavaScript using the jQuery AJAX method it always fails. Here is a code snippet of what I'm trying to do...
$.ajax({
url: "relyingPartySite/Controller/Action",
data: { foobar },
dataType: "json",
type: "POST",
async: false,
cache: false,
success: function (data) {
// do something here
},
error: function (data, status) {
alert(status);
}
});
The issue is that AD FS uses JavaScript to post a hidden html form to the relying party.
When tracing with Fiddler I can see it get to the AD FS site and return this html form which should post and redirect to the controller action authenticated. The problem is this form is coming back as the result of the ajax request and obviously going to fail with a parser error since the ajax request expects json from the controller action. It seems like this would be a common scenario, so what is the proper way to communicate with AD FS from AJAX and handle this redirection?
You have two options.
More info here.
The first is to share a session cookie between an entry application (one that is HTML based) and your API solutions. You configure both applications to use the same WIF cookie. This only works if both applications are on the same root domain.
See the above post or this stackoverflow question.
The other option is to disable the passiveRedirect for AJAX requests (as Gutek's answer). This will return a http status code of 401 which you can handle in Javascript.
When you detect the 401, you load a dummy page (or a "Authenticating" dialog which could double as a login dialog if credentials need to be given again) in an iFrame. When the iFrame has completed you then attempt the call again. This time the session cookie will be present on the call and it should succeed.
//Requires Jquery 1.9+
var webAPIHtmlPage = "http://webapi.somedomain/preauth.html"
function authenticate() {
return $.Deferred(function (d) {
//Potentially could make this into a little popup layer
//that shows we are authenticating, and allows for re-authentication if needed
var iFrame = $("<iframe></iframe>");
iFrame.hide();
iFrame.appendTo("body");
iFrame.attr('src', webAPIHtmlPage);
iFrame.load(function () {
iFrame.remove();
d.resolve();
});
});
};
function makeCall() {
return $.getJSON(uri)
.then(function(data) {
return $.Deferred(function(d) { d.resolve(data); });
},
function(error) {
if (error.status == 401) {
//Authenticating,
//TODO:should add a check to prevnet infinite loop
return authenticate().then(function() {
//Making the call again
return makeCall();
});
} else {
return $.Deferred(function(d) {
d.reject(error);
});
}
});
}
If you do not want to receive HTML with the link you can handle AuthorizationFailed on WSFederationAuthenticationModule and set RedirectToIdentityProvider to false on Ajax calls only.
for example:
FederatedAuthentication.WSFederationAuthenticationModule.AuthorizationFailed += (sender, e) =>
{
if (Context.Request.RequestContext.HttpContext.Request.IsAjaxRequest())
{
e.RedirectToIdentityProvider = false;
}
};
This with Authorize attribute will return you status code 401 and if you want to have something different, then you can implement own Authorize attribute and write special code on Ajax Request.
In the project which I currently work with, we had the same issue with SAML token expiration on the clientside and causing issues with ajax calls. In our particular case we needed all requests to be enqueud after the first 401 is encountered and after successful authentication all of them could be resent. The authentication uses the iframe solution suggested by Adam Mills, but also goes a little further in case user credentials need to be entered, which is done by displaying a dialog informing the user to login on an external view (since ADFS does not allow displaying login page in an iframe atleast not default configuration) during which waiting request are waiting to be finished but the user needs to login on from an external page. The waiting requests can also be rejected if user chooses to Cancel and in those cases jquery error will be called for each request.
Here's a link to a gist with the example code:
https://gist.github.com/kavhad/bb0d8e4a446496a6c05a
Note my code is based on usage of jquery for handling all ajax request. If your ajax request are being handled by vanilla javascript, other libraries or frameworks then you can perhaps find some inspiration in this example. The usage of jquery ui is only because of the dialog and stands for a small portion of the code which could easly be swapped out.
Update
Sorry I changed my github account name and that's why link did not work. It should work now.
First of all you say you are trying to make an ajax call to another website, does your call conforms to same origin policy of web browsers? If it does then you are expecting html as a response from your server, changedatatype of the ajax call to dataType: "html", then insert the form into your DOM.
Perhaps the 2 first posts of this serie will help you. They consider ADFS and AJAX requests
What I think I would try to do is to see why the authentication cookies are not transmitted through ajax, and find a mean to send them with my request. Or wrap the ajax call in a function that pre authenticate by retrieving the html form, appending it hidden to the DOM, submitting it (it will hopefully set the good cookies) then send the appropriate request you wanted to send originally
You can do only this type of datatype
"xml": Treat the response as an XML document that can be processed via jQuery.
"html": Treat the response as HTML (plain text); included script tags are evaluated.
"script": Evaluates the response as JavaScript and evaluates it.
"json": Evaluates the response as JSON and sends a JavaScript Object to the success callback.
If you can see in your fiddler that is returning only html then change your data type to html or if that only a script code then you can use script.
You should create a file anyname like json.php and then put the connection to the relayparty website this should works
$.ajax({
url: "json.php",
data: { foobar },
dataType: "json",
type: "POST",
async: false,
cache: false,
success: function (data) {
// do something here
},
error: function (data, status) {
alert(status);
}
});

Capture redirect location of javascript XMLHttpRequest

I know that you can't, when using an XMLHttpRequest, intercept a redirect or prevent it, as the browser will transparently follow it, but is it possible to either
A. Determine whether a request redirected, or
B. Determine where it redirected to? (assuming that the response gives no hints)
Example code:
$.post("/my-url-that-redirects/", {},
function(response, statusCode, xmlHttpRequest){
//Somehow grab the location it redirected to
}
);
In my case, firebug will first show a POST to the url, then a GET to the redirected url. Can that GET location be captured?
1) Use different status code than 301 (2**) (if request by ajax) and handle redirection on client side:
var STATUS = {
REDIRECT: 280
};
$.post('/redirected', {}, function(response, status, request) {
if (status == STATUS.REDIRECT) {
// you need to return the redirect url
location.href = response.redirectUrl;
} else {
$('#content').html(request.responseText);
}
});
2) DO NOT REDIRECT:
I use that in "redirect pattern" = redirecting after post request (you don't want to allow user to refresh the post request, etc..)
With ajax request, this is not necessary, so when the post request is ajax, I do forward instead (just forward to different controller - depends on your server-side framework, or what you are using...). POST requests are not cached by browsers.
Actually, I don't know what's the reason you need that, so this might not be so useful for you. This is helpful when server returns different responses for ajax requests than common requests, because when browser redirect ajax request, the redirected request is not XMLHttpRequest...
[updated]
You can access headers (of redirected request) like that:
$.post('redirected', {}, function(r, s, req) {
req.getAllResponseHeaders();
req.getResponseHeader('Location');
});
There should be 'Location' header, but it depends on the server, which headers are sent back...
After 4 years now it's possible to find the last redirect location using responseURL from XHR instance in Chrome 42+ (Opera 29+) and Firefox 39+ but it's not available in IE, Edge or safari yet.

How to manage a redirect request after a jQuery Ajax call

I'm using $.post() to call a servlet using Ajax and then using the resulting HTML fragment to replace a div element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the div element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed.
How can I manage a redirect directive from an Ajax call with jQuery 1.2.6?
I read this question and implemented the approach that has been stated regarding setting the response HTTP status code to 278 in order to avoid the browser transparently handling the redirects. Even though this worked, I was a little dissatisfied as it is a bit of a hack.
After more digging around, I ditched this approach and used JSON. In this case, all responses to AJAX requests have the status code 200 and the body of the response contains a JSON object that is constructed on the server. The JavaScript on the client can then use the JSON object to decide what it needs to do.
I had a similar problem to yours. I perform an AJAX request that has 2 possible responses: one that redirects the browser to a new page and one that replaces an existing HTML form on the current page with a new one. The jQuery code to do this looks something like:
$.ajax({
type: "POST",
url: reqUrl,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
} else {
// data.form contains the HTML for the replacement form
$("#myform").replaceWith(data.form);
}
}
});
The JSON object "data" is constructed on the server to have 2 members: data.redirect and data.form. I found this approach to be much better.
I solved this issue by:
Adding a custom header to the response:
public ActionResult Index(){
if (!HttpContext.User.Identity.IsAuthenticated)
{
HttpContext.Response.AddHeader("REQUIRES_AUTH","1");
}
return View();
}
Binding a JavaScript function to the ajaxSuccess event and checking to see if the header exists:
$(document).ajaxSuccess(function(event, request, settings) {
if (request.getResponseHeader('REQUIRES_AUTH') === '1') {
window.location = '/';
}
});
No browsers handle 301 and 302 responses correctly. And in fact the standard even says they should handle them "transparently" which is a MASSIVE headache for Ajax Library vendors. In Ra-Ajax we were forced into using HTTP response status code 278 (just some "unused" success code) to handle transparently redirects from the server...
This really annoys me, and if someone here have some "pull" in W3C I would appreciate that you could let W3C know that we really need to handle 301 and 302 codes ourselves...! ;)
The solution that was eventually implemented was to use a wrapper for the callback function of the Ajax call and in this wrapper check for the existence of a specific element on the returned HTML chunk. If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actual callback function.
For example, our wrapper function was something like:
function cbWrapper(data, funct){
if($("#myForm", data).length > 0)
top.location.href="login.htm";//redirection
else
funct(data);
}
Then, when making the Ajax call we used something like:
$.post("myAjaxHandler",
{
param1: foo,
param2: bar
},
function(data){
cbWrapper(data, myActualCB);
},
"html"
);
This worked for us because all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.
I like Timmerz's method with a slight twist of lemon. If you ever get returned contentType of text/html when you're expecting JSON, you are most likely being redirected. In my case, I just simply reload the page, and it gets redirected to the login page. Oh, and check that the jqXHR status is 200, which seems silly, because you are in the error function, right? Otherwise, legitimate error cases will force an iterative reload (oops)
$.ajax(
error: function (jqXHR, timeout, message) {
var contentType = jqXHR.getResponseHeader("Content-Type");
if (jqXHR.status === 200 && contentType.toLowerCase().indexOf("text/html") >= 0) {
// assume that our login has expired - reload our current page
window.location.reload();
}
});
Use the low-level $.ajax() call:
$.ajax({
url: "/yourservlet",
data: { },
complete: function(xmlHttp) {
// xmlHttp is a XMLHttpRquest object
alert(xmlHttp.status);
}
});
Try this for a redirect:
if (xmlHttp.code != 200) {
top.location.href = '/some/other/page';
}
I just wanted to share my approach as this might it might help someone:
I basically included a JavaScript module which handles the authentication stuff like displaying the username and also this case handling the redirect to the login page.
My scenario: We basically have an ISA server in between which listens to all requests and responds with a 302 and a location header to our login page.
In my JavaScript module my initial approach was something like
$(document).ajaxComplete(function(e, xhr, settings){
if(xhr.status === 302){
//check for location header and redirect...
}
});
The problem (as many here already mentioned) is that the browser handles the redirect by itself wherefore my ajaxComplete callback got never called, but instead I got the response of the already redirected Login page which obviously was a status 200. The problem: how do you detect whether the successful 200 response is your actual login page or just some other arbitrary page??
The solution
Since I was not able to capture 302 redirect responses, I added a LoginPage header on my login page which contained the url of the login page itself. In the module I now listen for the header and do a redirect:
if(xhr.status === 200){
var loginPageRedirectHeader = xhr.getResponseHeader("LoginPage");
if(loginPageRedirectHeader && loginPageRedirectHeader !== ""){
window.location.replace(loginPageRedirectHeader);
}
}
...and that works like charm :). You might wonder why I include the url in the LoginPage header...well basically because I found no way of determining the url of GET resulting from the automatic location redirect from the xhr object...
I know this topic is old, but I'll give yet another approach I've found and previously described here. Basically I'm using ASP.MVC with WIF (but this is not really important for the context of this topic - answer is adequate no matter which frameworks are used. The clue stays unchanged - dealing with issues related to authentication failures while performing ajax requests).
The approach shown below can be applied to all ajax requests out of the box (if they do not redefine beforeSend event obviously).
$.ajaxSetup({
beforeSend: checkPulse,
error: function (XMLHttpRequest, textStatus, errorThrown) {
document.open();
document.write(XMLHttpRequest.responseText);
document.close();
}
});
Before any ajax request is performed CheckPulse method is invoked (the controller method which can be anything simplest):
[Authorize]
public virtual void CheckPulse() {}
If user is not authenticated (token has expired) such method cannot be accessed (protected by Authorize attribute). Because the framework handles authentication, while token expires, it puts http status 302 to the response. If you don't want your browser to handle 302 response transparently, catch it in Global.asax and change response status - for example to 200 OK. Additionally, add header, which instructs you to process such response in special way (later at the client side):
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 302
&& (new HttpContextWrapper(Context)).Request.IsAjaxRequest())
{
Context.Response.StatusCode = 200;
Context.Response.AddHeader("REQUIRES_AUTH", "1");
}
}
Finally at the client side check for such custom header. If present - full redirection to logon page should be done (in my case window.location is replaced by url from request which is handled automatically by my framework).
function checkPulse(XMLHttpRequest) {
var location = window.location.href;
$.ajax({
url: "/Controller/CheckPulse",
type: 'GET',
async: false,
beforeSend: null,
success:
function (result, textStatus, xhr) {
if (xhr.getResponseHeader('REQUIRES_AUTH') === '1') {
XMLHttpRequest.abort(); // terminate further ajax execution
window.location = location;
}
}
});
}
I think a better way to handle this is to leverage the existing HTTP protocol response codes, specifically 401 Unauthorized.
Here is how I solved it:
Server side: If session expires, and request is ajax. send a 401 response code header
Client side: Bind to the ajax events
$('body').bind('ajaxSuccess',function(event,request,settings){
if (401 == request.status){
window.location = '/users/login';
}
}).bind('ajaxError',function(event,request,settings){
if (401 == request.status){
window.location = '/users/login';
}
});
IMO this is more generic and you are not writing some new custom spec/header. You also should not have to modify any of your existing ajax calls.
Edit: Per #Rob's comment below, 401 (the HTTP status code for authentication errors) should be the indicator. See 403 Forbidden vs 401 Unauthorized HTTP responses for more detail. With that being said some web frameworks use 403 for both authentication AND authorization errors - so adapt accordingly. Thanks Rob.
I resolved this issue like this:
Add a middleware to process response, if it is a redirect for an ajax request, change the response to a normal response with the redirect url.
class AjaxRedirect(object):
def process_response(self, request, response):
if request.is_ajax():
if type(response) == HttpResponseRedirect:
r = HttpResponse(json.dumps({'redirect': response['Location']}))
return r
return response
Then in ajaxComplete, if the response contains redirect, it must be a redirect, so change the browser's location.
$('body').ajaxComplete(function (e, xhr, settings) {
if (xhr.status == 200) {
var redirect = null;
try {
redirect = $.parseJSON(xhr.responseText).redirect;
if (redirect) {
window.location.href = redirect.replace(/\?.*$/, "?next=" + window.location.pathname);
}
} catch (e) {
return;
}
}
}
Another solution I found (especially useful if you want to set a global behaviour) is to use the $.ajaxsetup() method together with the statusCode property. Like others pointed out, don't use a redirect statuscode (3xx), instead use a 4xx statuscode and handle the redirect client-side.
$.ajaxSetup({
statusCode : {
400 : function () {
window.location = "/";
}
}
});
Replace 400 with the statuscode you want to handle. Like already mentioned 401 Unauthorized could be a good idea. I use the 400 since it's very unspecific and I can use the 401 for more specific cases (like wrong login credentials). So instead of redirecting directly your backend should return a 4xx error-code when the session timed out and you you handle the redirect client-side. Works perfect for me even with frameworks like backbone.js
I have a simple solution that works for me, no server code change needed...just add a tsp of nutmeg...
$(document).ready(function ()
{
$(document).ajaxSend(
function(event,request,settings)
{
var intercepted_success = settings.success;
settings.success = function( a, b, c )
{
if( request.responseText.indexOf( "<html>" ) > -1 )
window.location = window.location;
else
intercepted_success( a, b, c );
};
});
});
I check the presence of html tag, but you can change the indexOf to search for whatever unique string exists in your login page...
Most of the given solutions use a workaround, using an extra header or an inappropiate HTTP code. Those solutions will most probably work but feel a bit 'hacky'. I've come up with another solution.
We're using WIF which is configured to redirect (passiveRedirectEnabled="true") on a 401 response. The redirect is usefull when handling normal requests but won't work for AJAX requests (since browsers won't execute the 302/redirect).
Using the following code in your global.asax you can disable the redirect for AJAX requests:
void WSFederationAuthenticationModule_AuthorizationFailed(object sender, AuthorizationFailedEventArgs e)
{
string requestedWithHeader = HttpContext.Current.Request.Headers["X-Requested-With"];
if (!string.IsNullOrEmpty(requestedWithHeader) && requestedWithHeader.Equals("XMLHttpRequest", StringComparison.OrdinalIgnoreCase))
{
e.RedirectToIdentityProvider = false;
}
}
This allows you to return 401 responses for AJAX requests, which your javascript can then handle by reloading the page. Reloading the page will throw a 401 which will be handled by WIF (and WIF will redirect the user to the login page).
An example javascript to handle 401 errors:
$(document).ajaxError(function (event, jqxhr, settings, exception) {
if (jqxhr.status == 401) { //Forbidden, go to login
//Use a reload, WIF will redirect to Login
location.reload(true);
}
});
This problem may appear then using ASP.NET MVC RedirectToAction method. To prevent form displaying the response in div you can simply do some kind of ajax response filter for incomming responses with $.ajaxSetup. If the response contains MVC redirection you can evaluate this expression on JS side. Example code for JS below:
$.ajaxSetup({
dataFilter: function (data, type) {
if (data && typeof data == "string") {
if (data.indexOf('window.location') > -1) {
eval(data);
}
}
return data;
}
});
If data is: "window.location = '/Acount/Login'" above filter will catch that and evaluate to make the redirection instead of letting the data to be displayed.
Putting together what Vladimir Prudnikov and Thomas Hansen said:
Change your server-side code to detect if it's an XHR. If it is, set the response code of the redirect to 278.
In django:
if request.is_ajax():
response.status_code = 278
This makes the browser treat the response as a success, and hand it to your Javascript.
In your JS, make sure the form submission is via Ajax, check the response code and redirect if needed:
$('#my-form').submit(function(event){
event.preventDefault();
var options = {
url: $(this).attr('action'),
type: 'POST',
complete: function(response, textStatus) {
if (response.status == 278) {
window.location = response.getResponseHeader('Location')
}
else { ... your code here ... }
},
data: $(this).serialize(),
};
$.ajax(options);
});
<script>
function showValues() {
var str = $("form").serialize();
$.post('loginUser.html',
str,
function(responseText, responseStatus, responseXML){
if(responseStatus=="success"){
window.location= "adminIndex.html";
}
});
}
</script>
Let me just quote again the problem as described by #Steg
I had a similar problem to yours. I perform an ajax request that has 2
possible responses: one that redirects the browser to a new page and
one that replaces an existing HTML form on the current page with a new
one.
IMHO this is a real challenge and will have to be officially extended to the current HTTP standards.
I believe the new Http Standard will be to use a new status-code.
meaning: currently 301/302 tells the browser to go and fetch the content of this request to a new location.
In the extended standard, it will say that if the response status: 308 (just an example), then the browser should redirect the main page to the location provided.
That being said; I'm inclined to already mimic this future behavior, and therefore when a document.redirect is needed, I have the server respond as:
status: 204 No Content
x-status: 308 Document Redirect
x-location: /login.html
When JS gets the "status: 204", it checks for the existence of the x-status: 308 header, and does a document.redirect to the page provided in the location header.
Does this make any sense to you?
Try
$(document).ready(function () {
if ($("#site").length > 0) {
window.location = "<%= Url.Content("~") %>" + "Login/LogOn";
}
});
Put it on the login page. If it was loaded in a div on the main page, it will redirect til the login page. "#site" is a id of a div which is located on all pages except login page.
While the answers seem to work for people if you're using Spring Security I have found extending LoginUrlAuthenticationEntryPoint and adding specific code to handle AJAX more robust. Most of the examples intercept all redirects not just authentication failures. This was undesirable for the project I work on. You may find the need to also extend ExceptionTranslationFilter and override the "sendStartAuthentication" method to remove the caching step if you don't want the failed AJAX request cached.
Example AjaxAwareAuthenticationEntryPoint:
public class AjaxAwareAuthenticationEntryPoint extends
LoginUrlAuthenticationEntryPoint {
public AjaxAwareAuthenticationEntryPoint(String loginUrl) {
super(loginUrl);
}
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
if (isAjax(request)) {
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Please re-authenticate yourself");
} else {
super.commence(request, response, authException);
}
}
public static boolean isAjax(HttpServletRequest request) {
return request != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}
}
Sources:
1, 2
I solved this by putting the following in my login.php page.
<script type="text/javascript">
if (top.location.href.indexOf('login.php') == -1) {
top.location.href = '/login.php';
}
</script>
Some might find the below useful:
I wanted clients to be redirected to the login page for any rest-action that is sent without an authorization token. Since all of my rest-actions are Ajax based, I needed a good generic way to redirect to the login page instead of handling the Ajax success function.
This is what I've done:
On any Ajax request my server will return a Json 200 response "NEED TO AUTHENTICATE" (if the client needs to authenticate).
Simple example in Java (server side):
#Secured
#Provider
#Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
private final Logger m_logger = LoggerFactory.getLogger(AuthenticationFilter.class);
public static final String COOKIE_NAME = "token_cookie";
#Override
public void filter(ContainerRequestContext context) throws IOException {
// Check if it has a cookie.
try {
Map<String, Cookie> cookies = context.getCookies();
if (!cookies.containsKey(COOKIE_NAME)) {
m_logger.debug("No cookie set - redirect to login page");
throw new AuthenticationException();
}
}
catch (AuthenticationException e) {
context.abortWith(Response.ok("\"NEED TO AUTHENTICATE\"").type("json/application").build());
}
}
}
In my Javascript I've added the following code:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
var originalSuccess = options.success;
options.success = function(data) {
if (data == "NEED TO AUTHENTICATE") {
window.location.replace("/login.html");
}
else {
originalSuccess(data);
}
};
});
And that's about it.
in the servlet you should put
response.setStatus(response.SC_MOVED_PERMANENTLY);
to send the '301' xmlHttp status you need for a redirection...
and in the $.ajax function you should not use the .toString() function..., just
if (xmlHttp.status == 301) {
top.location.href = 'xxxx.jsp';
}
the problem is it is not very flexible, you can't decide where you want to redirect..
redirecting through the servlets should be the best way. but i still can not find the right way to do it.
I just wanted to latch on to any ajax requests for the entire page. #SuperG got me started. Here is what I ended up with:
// redirect ajax requests that are redirected, not found (404), or forbidden (403.)
$('body').bind('ajaxComplete', function(event,request,settings){
switch(request.status) {
case 301: case 404: case 403:
window.location.replace("http://mysite.tld/login");
break;
}
});
I wanted to specifically check for certain http status codes to base my decision on. However, you can just bind to ajaxError to get anything other than success (200 only perhaps?) I could have just written:
$('body').bind('ajaxError', function(event,request,settings){
window.location.replace("http://mysite.tld/login");
}
If you also want to pass the values then you can also set the session variables and access
Eg:
In your jsp you can write
<% HttpSession ses = request.getSession(true);
String temp=request.getAttribute("what_you_defined"); %>
And then you can store this temp value in your javascript variable and play around
I didn't have any success with the header solution - they were never picked up in my ajaxSuccess / ajaxComplete method. I used Steg's answer with the custom response, but I modified the JS side some. I setup a method that I call in each function so I can use standard $.get and $.post methods.
function handleAjaxResponse(data, callback) {
//Try to convert and parse object
try {
if (jQuery.type(data) === "string") {
data = jQuery.parseJSON(data);
}
if (data.error) {
if (data.error == 'login') {
window.location.reload();
return;
}
else if (data.error.length > 0) {
alert(data.error);
return;
}
}
}
catch(ex) { }
if (callback) {
callback(data);
}
}
Example of it in use...
function submitAjaxForm(form, url, action) {
//Lock form
form.find('.ajax-submit').hide();
form.find('.loader').show();
$.post(url, form.serialize(), function (d) {
//Unlock form
form.find('.ajax-submit').show();
form.find('.loader').hide();
handleAjaxResponse(d, function (data) {
// ... more code for if auth passes ...
});
});
return false;
}
Finally, I solve the problem by adding a custom HTTP Header. Just before response for every request in server side, i add the current requested url to response's header.
My application type on server is Asp.Net MVC, and it has a good place to do it. in Global.asax i implemented the Application_EndRequest event so:
public class MvcApplication : System.Web.HttpApplication
{
// ...
// ...
protected void Application_EndRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
app.Context.Response.Headers.Add("CurrentUrl",app.Context. Request.CurrentExecutionFilePath);
}
}
It works perfect for me! Now in every response of the JQuery $.post i have the requested url and also other response headers which comes as result of POST method by status 302, 303 ,... .
and other important thing is that there is no need to modify code on server side nor client side.
and the next is the ability to get access to the other information of post action such errors, messages, and ..., In this way.
I posted this, maybe help someone :)
I was having this problem on a django app I'm tinkering with (disclaimer: I'm tinkering to learn, and am in no way an expert). What I wanted to do was use jQuery ajax to send a DELETE request to a resource, delete it on the server side, then send a redirect back to (basically) the homepage. When I sent HttpResponseRedirect('/the-redirect/') from the python script, jQuery's ajax method was receiving 200 instead of 302. So, what I did was to send a response of 300 with:
response = HttpResponse(status='300')
response['Location'] = '/the-redirect/'
return response
Then I sent/handled the request on the client with jQuery.ajax like so:
<button onclick="*the-jquery*">Delete</button>
where *the-jquery* =
$.ajax({
type: 'DELETE',
url: '/resource-url/',
complete: function(jqxhr){
window.location = jqxhr.getResponseHeader('Location');
}
});
Maybe using 300 isn't "right", but at least it worked just like I wanted it to.
PS :this was a huge pain to edit on the mobile version of SO. Stupid ISP put my service cancellation request through right when I was done with my answer!
You can also hook XMLHttpRequest send prototype. This will work for all sends (jQuery/dojo/etc) with one handler.
I wrote this code to handle a 500 page expired error, but it should work just as well to trap a 200 redirect. Ready the wikipedia entry on XMLHttpRequest onreadystatechange about the meaning of readyState.
// Hook XMLHttpRequest
var oldXMLHttpRequestSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function() {
//console.dir( this );
this.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 500 && this.responseText.indexOf("Expired") != -1) {
try {
document.documentElement.innerHTML = this.responseText;
} catch(error) {
// IE makes document.documentElement read only
document.body.innerHTML = this.responseText;
}
}
};
oldXMLHttpRequestSend.apply(this, arguments);
}
I got a working solulion using the answers from #John and #Arpad link and #RobWinch link
I use Spring Security 3.2.9 and jQuery 1.10.2.
Extend Spring's class to cause 4XX response only from AJAX requests:
public class CustomLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
public CustomLoginUrlAuthenticationEntryPoint(final String loginFormUrl) {
super(loginFormUrl);
}
// For AJAX requests for user that isn't logged in, need to return 403 status.
// For normal requests, Spring does a (302) redirect to login.jsp which the browser handles normally.
#Override
public void commence(final HttpServletRequest request,
final HttpServletResponse response,
final AuthenticationException authException)
throws IOException, ServletException {
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
} else {
super.commence(request, response, authException);
}
}
}
applicationContext-security.xml
<security:http auto-config="false" use-expressions="true" entry-point-ref="customAuthEntryPoint" >
<security:form-login login-page='/login.jsp' default-target-url='/index.jsp'
authentication-failure-url="/login.jsp?error=true"
/>
<security:access-denied-handler error-page="/errorPage.jsp"/>
<security:logout logout-success-url="/login.jsp?logout" />
...
<bean id="customAuthEntryPoint" class="com.myapp.utils.CustomLoginUrlAuthenticationEntryPoint" scope="singleton">
<constructor-arg value="/login.jsp" />
</bean>
...
<bean id="requestCache" class="org.springframework.security.web.savedrequest.HttpSessionRequestCache">
<property name="requestMatcher">
<bean class="org.springframework.security.web.util.matcher.NegatedRequestMatcher">
<constructor-arg>
<bean class="org.springframework.security.web.util.matcher.MediaTypeRequestMatcher">
<constructor-arg>
<bean class="org.springframework.web.accept.HeaderContentNegotiationStrategy"/>
</constructor-arg>
<constructor-arg value="#{T(org.springframework.http.MediaType).APPLICATION_JSON}"/>
<property name="useEquals" value="true"/>
</bean>
</constructor-arg>
</bean>
</property>
</bean>
In my JSPs, add a global AJAX error handler as shown here
$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
if ( jqxhr.status === 403 ) {
window.location = "login.jsp";
} else {
if(thrownError != null) {
alert(thrownError);
} else {
alert("error");
}
}
});
Also, remove existing error handlers from AJAX calls in JSP pages:
var str = $("#viewForm").serialize();
$.ajax({
url: "get_mongoDB_doc_versions.do",
type: "post",
data: str,
cache: false,
async: false,
dataType: "json",
success: function(data) { ... },
// error: function (jqXHR, textStatus, errorStr) {
// if(textStatus != null)
// alert(textStatus);
// else if(errorStr != null)
// alert(errorStr);
// else
// alert("error");
// }
});
I hope it helps others.
Update1
I found that I needed to add the option (always-use-default-target="true") to the form-login config.
This was needed since after an AJAX request gets redirected to the login page (due to expired session), Spring remembers the previous AJAX request and auto redirects to it after login. This causes the returned JSON to be displayed on the browser page. Of course, not what I want.
Update2
Instead of using always-use-default-target="true", use #RobWinch example of blocking AJAX requests from the requstCache. This allows normal links to be redirected to their original target after login, but AJAX go to the home page after login.
As alternative to ajax, there is a new Fetch API being developed, which allows manual redirect handling. You need to check if the current browser support is enough for your needs.

Categories

Resources