views:

275

answers:

1

Hi,

Here is my problem: I'm developing a system that can be polled to retrieve dynamic data. It's in Grails, and when I do a request on a certain controller action, say "http://localhost:8080/foo/bar", a JSON list is returned containing the latest data.

For added security and functionality, I protected my page using Spring Security (Grails Acegi plugin), with Basic Authentication enabled. When you log in, the system automatically loads information regarding your user profile, and that changes the data that is returned. So, authentication is mandatory.

This works: I can poll my action from any browser, and the data will be returned. I have a JavaScript script in my Grails application that calls this URL.

The problem is that I would like to externalize my JavaScript script to distribute it to customers, so they can build their own HTML file, plug in my JavaScript file, and be able to access my data (kind of like an API) using AJAX. Like so:

$.ajax(url: urlWithParams, 
       method: 'GET', 
       beforeLoad: function(xhr) { 
           xhr.setRequestHeader('Authorization', authString);
       },
       success: myFunction
});

However, it doesn't work. First of all, I know cross-domain GET requests are tricky. But in my case, I use Basic Authentication, which is trickier, because I need to put the credentials into the XmlHttpRequest directly, and that produces preflighted requests in Firefox (replacing GET by OPTIONS), and my Grails application doesn't deal with it.

My problem is very specific. I use Basic Authentication to prevent malicious access, however I can't access my application using proper credentials because of some cross-domain restrictions!

What should I do! I tried with an IFrame, but I can't get the page content (I get an "Access Denied" error - yet again cross-domain restrictions).

Also, jQuery username and password fields in the ajax() function don't work.

Could I do a simple AJAX GET request on an unprotected page, sending credentials as parameters, and then the page would redirect to the protected page using the credentials? The browser wouldn't mangle the request, but can I do a redirect with Basic Authentication credentials?

I have a feeling that it won't work (something to do with the redirect, which generates a new request, etc...). Am I right, or should it work?

Could JSONP solve this problem? I don't know how to integrate Basic Authentication using JSONP, however...

Thank you very much!

A: 

I solved my question using JSONP. I modified my application so as not require basic authentification for the AJAX call. The $.getJSON() method from jQuery did the trick.

Guillaume Gervais
Yours was a good question, but this is a horrible answer. You just simply disable authentication if the request is made with `getJSON`?
Roatin Marth