6

I have looked at the following questions here on stackoverflow with no luck in what im trying to do.

Ajax Authorization Request headers fails again and again

jQuery Ajax Unauthorized 401 Error

Sending credentials with cross-domain posts?

Here is my code that I currently have:

 $(document).ready(function() { $.ajax({ url: 'http://sample.domain.com/script.php?name1=value1&jsonp=?', type: 'GET', dataType: 'json', contentType: "application/json", beforeSend: function(xhr) { xhr.setRequestHeader("Authentication", "Basic ZnJvbWFwcGx********uOnRoM24zcmQ1UmgzcjM=") //Some characters have been replaced for security but this is a true BASE64 of "username:password" }, success: function(data){ alert(data); } }); }); </script> 

The subdomain I have is password protected by an .htpasswd file. The login of the site works just fine for me using the username/password combo used in the base64 encode.

Im running this script on a different domain than the one that the url is on which is why i have the jsonp=? in the url

The response im getting from the console in the browser is: GET http://sample.domain.com/script.php?name1=value1&jsonp=jsonp1334177732136 401 (Authorization Required)

3
  • Why are you using basic auth here? Your JS will expose the base64'd password to the world, so it won't offer any security. Or have I misunderstood your situation? Commented Apr 11, 2012 at 21:03
  • To be honest every method is unsafe via HTTP. That's why HTTPS exists. Commented Apr 11, 2012 at 21:08
  • The security here is not the question. This is just a sample of what I have. Ive pulled this down to the basic to try and get something to work. After I have the basic working, Ill make it secure. Commented Apr 11, 2012 at 21:28

2 Answers 2

7

The header name is Authorization, and you are sending "Authentication"

e.g.

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtBmU=

Sign up to request clarification or add additional context in comments.

Comments

4

JSONP uses a script tag proxy. It wouldn't support custom headers. Are you in control of the endpoint? If so look into enabling CORS, or pass the authentication key in the GET string.

When using jsonp JQuery converts your URL "ajax" request to:

<script src="[endpoint]"></script> 

it then writes a random function

var json9409d0sf0d9s0df90 = function() { //some callback logic here. } 

and appends ?callback=json9409d0sf0d9s0df90

your server then says

echo $_GET['callback] . "(" . $json . ")"; 

and sends that back as the response so

json9409d0sf0d9s0df90({some: data}); 

is exexcuted by the browser and handled by jQuery's magical handlers that make it respond like a normal ajax callback.

AFAIK, <script src=""></script> asset loads wont take custom headers by any standard browser.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.