I was trying to call an ajax request with Basic authentication, for that i added the following code,
url: appSettings.dataURL+'/app/signature',
type: 'GET',
crossDomain: true,
dataType: 'html',
context : this,
cache : true,
headers: {"Authorization": "Basic " + btoa('username' + ":" + 'password')}
This will make two requests, one with authentication and another without authentication when I inspect with network tab. Why?
See the screen shot,
Is it possible to avoid this?
Note: This happens only for cross domain requests.
Cross-site requests follow certain rules for security. A simple, single request can be made if the only custom headers set are:
and the content type is one of:
You are sending the Authorization
header and requesting HTML, so by default that requires a "pre-flight request":
Unlike simple requests, "preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data.
The initial OPTIONS
request without Authorization
is safe because the server only needs to respond with Access-Control-*
headers that let the browser know if your full request is OK to proceed. Then your actual request with Authorization
is going through, so everything is working as expected.
The XMLHttpRequest object does let you specify you're sending a request with credentials and possibly switch to just one request:
xhrFields: { withCredentials: true }