1
votes

How do I make a cross origin request to a web service that uses HTTP Basic Auth?

My client is developed in jQuery and my RESTful/JSON web service has been modified so "cross-origin" headers are returned.

Client code:

$.ajax({
    url: "http://localhost:3000/applications", // external service
    async: false,
    beforeSend: function (req) {
        req.setRequestHeader("Authorization", "Basic "+ base64_value)
    },
    success: function (applications) { $.each(applications, function(i, app) {
        list.push(app)
    })}
})

The client code triggers both a OPTIONS and GET request (in Chrome). The OPTIONS request fails with a 401.

What headers should I use for GET requests and what headers should I use for OPTIONS requests? And which server response headers should be used for GET and OPTIONS?

I made a request to the service using cURL and exact same authorization header and this worked (i.e. same username/password as in JavaScript code). So I guess this is related to the headers and OPTIONS method.

1
try using :- type:"GET" or type:"POST" - Avichal Badaya
Adding type: "GET" did not help. - Parnas
The url works in my browser, so that authorization header is correct but it is not sent in OPTIONS request. - Parnas

1 Answers

0
votes

I didn't know this was possible, but after reading up on it, you can in fact do this. The bug with your code comes from the Header value you are defining in the beforeSend()

The Header Name is correct but here is how you must construct your value (you will need a Base64 encoder like base64.js)

var base64 = Base64.encode(username + ":" + password)

And then you can use your jQuery block as you have written it.