Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX POST Request Hide Basic Auth Credentials

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));             
    }
});
like image 626
Nathan_Sharktek Avatar asked Dec 03 '25 11:12

Nathan_Sharktek


1 Answers

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.

like image 136
MvdD Avatar answered Dec 05 '25 05:12

MvdD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!