4

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,

enter image description here

Is it possible to avoid this?

Note: This happens only for cross domain requests.

Matt S
  • 13,731
  • 4
  • 45
  • 70
Shijin TR
  • 6,709
  • 8
  • 37
  • 99
  • 1
    It probably is because cross-origin header is not set. Check out [this question](http://stackoverflow.com/questions/5507234/how-to-use-basic-auth-with-jquery-and-ajax) where basic auth in jQuery is already covered. – Sainan Apr 29 '16 at 07:35
  • 2
    The first request is a **preflight** request to check that the server accepts the request method and that credentials are allowed, this will only happen with a **CORS** request. AFAIK it is not possible to avoid this if you are making a cross domain request – Michael Doye Apr 29 '16 at 07:36

1 Answers1

2

Cross-site requests follow certain rules for security. A simple, single request can be made if the only custom headers set are:

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type

and the content type is one of:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

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 }
Matt S
  • 13,731
  • 4
  • 45
  • 70