3

I've been researching ways to send AJAX POST requests to my API and I'm trying to understand how to pass basic auth credentials correctly.

          Interface                    API

https://www.example.com/app/ -------> https://api.example.com/

Using this example I found on StackOverflow--couldn't anyone view the source of the JS, see my username and password in cleartext, and have access to all my API functions?

If so, how do I pass my username and password without showing it to the world?

$.ajax({  
    url: 'yoururl',
    username : username,
    password :password,
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    dataType: "text",
    xhrFields: 
    {
        withCredentials: true
    },
    beforeSend: function (xhr) { 
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));             
    }
});
Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30
Nathan_Sharktek
  • 407
  • 1
  • 5
  • 21

1 Answers1

3

Yes, if you hardcode your username and password in your JavaScript, the whole world will be able to see them and use them.

You should not use basic authentication to protect web APIs. There are several alternatives as I describe in this answer. My preference is with OAuth2. Using it from a JavaScript client, you want to look at the implicit flow, which is specifically for untrusted clients.

Community
  • 1
  • 1
MvdD
  • 22,082
  • 8
  • 65
  • 93