1

I am trying to send a request using ajax to a server which is protected by basic authentication with the following code:

$('document').ready(function(){
        $.ajax({
          url: "https://somesite.com/somefolder",
          type: "POST",
          dataType: 'jsonp',
          beforeSend: function(xhr) {
                xhr.setRequestHeader ("Authorization", "Basic " + btoa('myusername' + ":" + 'mypassword'));
            },
          success: function(data){
            console.log('SUCCESS!');
          },
          error: function () {
            console.log("error");
            }
        });         
});

So I provide the credentials in the beforeSend so my expectation would be that there would be no credential popup from the browser since I already provided the credentials but unfortunately when i run this code I get the popup to enter my credentials. I want to the code to provide these credentials.

user2924127
  • 6,034
  • 16
  • 78
  • 136
  • I've deleted my answer, thanks for the clarification. – Phil Jul 30 '18 at 16:25
  • It sounds like the site hosting your JS is giving you a 401, right? Not the site that you're trying to hit with ajax. – wholevinski Jul 30 '18 at 16:31
  • @wholevinski When the page loads I get no error in the console. The JQuery CDN I use works fine. The only thing that shows first in the authentication popup. If I enter the credentials it works fine, if I press cancel instead then I get a 401 (unauthorized) error as expected. I tried running a similar request in POSTMAN with the basic credentials added to the header and it works fine so the server is working fine – user2924127 Jul 30 '18 at 16:38
  • 1
    You can't send headers or do POST using `jsonp`. It is a script request not really ajax. Suspect you want `json` and need to check if api is CORS enabled. Postman is not subject to CORS restrictions – charlietfl Jul 30 '18 at 16:43
  • A plaintext password and username in a place where the user can view it is not much of a password right? – bassxzero Jul 30 '18 at 16:44

1 Answers1

0

Similar to this question, example using headers:

    $.ajax({
      url: "https://somesite.com/somefolder",
      type: "POST",
      dataType: 'jsonp',
      headers: {"Authorization": "Basic " + btoa('myusername' + ":" + 'mypassword')},
      success: function(data){
        console.log('SUCCESS!');
      },
      error: function () {
        console.log("error");
        }
    }); 
Gianmar
  • 505
  • 3
  • 13