Home > other >  XMLHttpRequest: How do I pass 'POST' parameters safely (username, password)?
XMLHttpRequest: How do I pass 'POST' parameters safely (username, password)?

Time:12-04

I have this code:

function RequestLogin() 
  {
      var request = new XMLHttpRequest();
      request.onreadystatechange = function() {
          if (this.readyState == 4) 
          {
              alert(this.responseURL);
          }
      };

      request.open('POST', 'http://myserver/login');
      request.setRequestHeader('Content-type', 'multipart/form-data');
      request.send('user=myUsername&password=myPassword');
    }

Is this considered "safe" If I use HTTPS instead of http://myserver/login? What it's not clear to me are the parameters that I have to bind in the request.send, what am I doing there? Am I appending them in the URL, therefore they're visible if someone sniffs the request? I used to create Form Object and pass it there, but it's not working in this case.

It's the only way I found to pass parameters to POST request, but am I not exposing the parameters anyway by doing 'user=myUsername&password=myPassword'?

Thanks

CodePudding user response:

If you POST to an HTTPS endpoint, yes, that'll be safe.

What it's not clear to me are the parameters that I have to bind in the request.send, what am I doing there?

You are sending that string as the request body., and you're sending it to the URL specified, request.open('POST', 'http://myserver/login');.

With HTTPS, both the path (/login) and request body are encrypted; snoopers will not be able to see the actual contents of either of them.

Am I appending them in the URL, therefore they're visible if someone sniffs the request?

No, they're not appended in the URL - if that was being done, the code would instead look something like

request.open('POST', 'http://myserver/login?foo=bar&baz=buzz');

Which would be quite strange for a POST - but if it was over HTTPS, it's still be safe, because all snoopers would be able to see is that you and https://myserver are having a conversation. They wouldn't be able to see which endpoint on myserver you're talking to (so, the /login? and everything that follows would be private), and they wouldn't be able to see the contents of the request either.

That said, it'd be better to .send the data as you're doing now

request.send(sensitiveInfo)

than to append the info to the URL because URLs are sometimes stored in the server logs. It's nowhere near as vulnerable as allowing any observer to see what's going on, but it's still not a good idea.

You also might consider whether you could use fetch instead of XMLHttpRequest - fetch is considered the more modern way of making requests. It uses Promises, is arguably more intuitive, and has been generally supported by browsers since 2015.

  • Related