sumit
sumit

Reputation: 11257

Authentication using XMLHTTPRequest

As we all know that using GET method for login (or sending sensitive information) is not suggested. I want to create login functionality using XMLHTTPRequest. Following are my steps:

  1. User enters username and password and clicks on Submit button
  2. Submit button invokes an XMLHTTPRequest
  3. XMLHTTPRequest sends the credential to a PHP page which will verify it
  4. If credentials are right then create session otherwise show error message without refreshing the login screen.

My question is:

How can I transfer login credentials to a PHP page using POST (securely)? If I am using the open method as shown below with GET then I think it is not secure. Can I replace GET with POST? If yes, then how to transfer credentials?

xmlhttp.open("GET","verifyCredentials.php",true);

Upvotes: 1

Views: 4966

Answers (4)

Gumbo
Gumbo

Reputation: 655129

To post data using POST method, set the method in open to POST, set the Content-Type request header field to application/x-www-form-urlencoded, encode your data accordingly, and pass it as parameter value to send:

xmlhttp.open("POST", "verifyCredentials.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(data);

You can use the encodeURIComponent function to encode your data:

function formUrlEncoded(params) {
    var data = "";
    for (var name in params) {
        if (!params.hasOwnProperty(name)) continue;
        if (data.length) data += "&";
        data += (encodeURIComponent(name) + "=" + encodeURIComponent(param)).replace(/%20/g, "+");
    }
    return data;
}
var data = formUrlEncoded({"foo":"bar", "baz":"quux"});

Note that with this the data is still transferred unprotected against eavesdropping.

Upvotes: 2

Keith
Keith

Reputation: 43024

If you want to do authentication over an insecure channel (you are not using HTTPS) you could use an HMAC based login protocol. HMAC can be used for user authentication.

I have an implementation of this available in Javascript (client) and Python (server side). You can use that as an example to start with, or find another implementation. There is probably a PHP implementation of it somewhere, but you will likely have to modify it for your needs.

Upvotes: 0

stewe
stewe

Reputation: 42612

The only difference of POST and GET is that POST sends the data in the http-body and not in the URL (headers), so both methods are not "secure" for transmitting login credentials. As mentioned, you should use https.

Upvotes: 1

Max
Max

Reputation: 8836

Send the md5 of the passwords in the password field. Then, on the server, you can further obfuscate it if you want.

Upvotes: 0

Related Questions