Search code examples
javascriptphpajaxhttpsxmlhttprequest

Is XMLHttpRequest secure over HTTPS?


I am developing a PHP/JS web application in which I make heavy use of the XMLHttpRequest object (for page updates / AJAX, etc.). Among many other areas, I use this in my user management code (login, signup, etc.). Specifically, I use it to send passwords in plain text through XMLHttpRequests (to then be hashed by the server and stored safely away in the database). To illustrate with a minimal example, the process looks something like this:

// Define the HTTP request parameters
var username = "my_username";
var password = "my_super_secure_password";
var addr = "/my_app/check_login";
var post = "ACTION=CREATE_USER&USERNAME=" + username + "&PASSWORD=" + password;

// Create the XMLHttpRequest object
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
     // AJAX stuff goes here!
}
xhttp.open("POST", addr, true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

// And away it goes!
xhttp.send(post);

Obviously, on my localhost setup (HTTP only with MAMP, no security), this works wonders. However, I am concerned about uploading this to my host server (HTTPS / SSL, etc.) and whether it will a) be successful and, most importantly, b) be secure.

I don't know whether the XMLHttpRequest object would automatically adjust to the same protocol the page is using - if not, sending the user's passwords through this would obviously pose a security risk. I would be very grateful if someone more competent than me could let me know - and, if this is in fact insecure, inform me of any alternative ways to use AJAX more securely.

Thanks!


Solution

  • Yes, sending the requests over HTTPS with XMLHttpRequest is as secure as sending them over HTTPS with fetch or normal form submission.

    I don't know whether the XMLHttpRequest object would automatically adjust to the same protocol the page is using

    That depends on the URL you are passing to the open() method, i.e. your addr. If it is a relative URL, then yes. If it is an absolute URL, you could send a HTTP request even from a page loaded over HTTPS - which is a bad idea, and you can guard against this happening accidentally (or even maliciously) with a content security policy to prevent mixed content.