0

I need to make a CORS request to server which uses basic authentication. I use jQuery 1.5.1 and have this code:

$.ajax({
    type: 'GET',
    global: true,
    url: theSource,
    crossDomain: true,
    beforeSend: function(xhr) { 
        xhr.withCredentials = true;
        xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
    },
    error: function (xhr, status, errorThrown) {
        alert(errorThrown + '\n' + status + '\n' + xhr.statusText);
    },
    success: function (data) {
        ABC.ABCconsole.log('Success');
        ABC.openAjaxSuccess(data);
    }
});

On a server side setted these headers:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization, Accept
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Origin: http://example.com

Unfortunately in response from server I have 401 Unauthorized error.

In a request I have these headers:

Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Host:example01.com
Origin:http://example.com
Referer:http://example.com/france/asd/qwes/business-nothing.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36

And in a response these headers:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization, Accept
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Origin: http://example.com
Content-Length:58
Content-Type:text/html
Date:Wed, 16 Jul 2014 09:42:00 GMT
Server:Microsoft-IIS/7.5
Set-Cookie:loc=phl;path=/;
WWW-Authenticate:Basic realm="example01.com"

May be you have any ideas why it happens?

UPD: As you can see in a request I don't see that my Authentication header is setted. If I running browser with --disable-web-security key everything works fine. And Authentication header is setted properly.

UPD2: Request fails on a http POST method. So may be problem is here?

Remote Address:111.111.11.12:80
Request URL:http://example01.com/asst/index.epx?id=569fe9d0-1515-423a-bae8-84265b6396a0&_=1405506291028
Request Method:OPTIONS
Status Code:401 Unauthorized
Petr Shypila
  • 1,261
  • 9
  • 23
  • 43
  • I think the server is responding with what it knows. Authorisation failed. Is the username and password correct? Run wireshark and look at the request at the network level and compare that to accessing the same page in your web browser, so check that the basic authentication is working, and tinker with it. Or use fiddler for the tinkering. Perhaps take a look here – Action Dan Jul 16 '14 at 10:10
  • @ActionDan unfortunately credentials are correct. If I requesting url from browser I get login form. Bot it doesn't work with jQuery CORS request. In a response i get only 401 error. – Petr Shypila Jul 16 '14 at 11:18

1 Answers1

0

Use Access-Control-Allow-Origin: * instead.

XIMRX
  • 1,972
  • 3
  • 25
  • 52