HTTP Basic Authentication with AJAX and php

1

I'm trying to do a simple password authentication using HTTP BA.

follow the codes: login.php

<?php

if(!(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']))){
   header('WWW-Authenticate: Basic realm="Restricted Area');
   header('HTTP/1.0 401 Unauthorized');
   die('Acesso Não Autorizado!');
}

$validPasswords = ["neto" => "1234"];//consulta ao banco para login e guardar em array ['login' = > 'Senha'];
$validUser = array_keys($validPasswords);
//recebe usuário e senha do cliente  
$user = $_SERVER['PHP_AUTH_USER'];
$pass = $_SERVER['PHP_AUTH_PW'];

$validate = (in_array($user, $validUser) && $pass = $validPasswords[$user]);

if (!$validate){
   header('WWW-Authenticate: Basic realm="Restricted Area');
   header('HTTP/1.0 401 Unauthorized');
   die('Acesso Não Autorizado!');
}

echo "ENTROU";
?>

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Autenticação HTTP</title>
        <meta charset="ISO-8859-1">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script></head><body><formname="cookieform" id="login" method="get">
            <input type="text" name="username" id="username" />
            <input type="password" name="password" id="password" />
            <input type="submit" name="sub" value="Submit" onclick="auth()" />
        </form>

   <script>
   var username = $("#username").val();
   var password = $("#password").val();

   function auth(){
      $.ajax({
         type: "GET",
         url: "login.php",
         dataType: 'json',
         async: false,
         data: '{"username": "' + username + '", "password" : "' + password + '"}',
         beforeSend: function (xhr) {
            xhr.setRequestHeader ("Authorization", "Basic " + btoa(function (user, password) {
                  var tok = user + ':' + password;
                  var hash = Base64.encode(tok);
                  return "Basic " + hash;
            }));
         },
         success: function (response){
            alert(response);
         },
         error: function (response){
            alert(response);
         }
      });
   }
   </script>
    </body>
</html>

I tried using XMLHttpRequest:

   function auth(){
      // using XMLHttpRequest
      var username = $("input#username").val();
      var password = $("input#password").val();
      var xhr = new XMLHttpRequest();
      xhr.open("GET", "login.php", true);
      xhr.withCredentials = true;
      xhr.setRequestHeader("Authorization",function (username, password) {
                  var tok = user + ':' + password;
                  var hash = Base64.encode(tok);
                  return 'Basic ' + hash;
            });
      xhr.onload = function () {
         console.log(xhr.responseText);
      };
      xhr.send();
}

Does not return any messages in the console. I changed console.log to alert, and nothing happens!

The browser tries to open the window requesting username and password, but soon after the window closes.

Login.php is working because I have tried accessing it directly in the browser and typing the data in the browser request.

I need to create this solution because I have to access data using secure endpoints through a mobile app.

EDIT:

I changed the open method of XMLHttpRequest:

xhr.open("GET", "login.php", true, user, pass);

and I put a print_r($_SERVER) in login.php

['PHP_AUTH_USER'] and ['PHP_AUTH_PW'] indices did not appear when printing the array ...

Now with XMLHttpRequest I'm getting the alert, with the array print ...

    
asked by anonymous 28.08.2018 / 02:46

1 answer

1

As far as I know setRequestHeader expect strings and not functions, this is wrong:

function (username, password) {
              var tok = user + ':' + password;
              var hash = Base64.encode(tok);
              return 'Basic ' + hash;
        }

And even if it auto executes the function yet, username and password are passed as parameters, that is will not get values from:

  var username = $("input#username").val();
  var password = $("input#password").val();

The XmlHttpRequest object already has parameters to pass the authorization value, so it should look like this:

function auth(){
  // using XMLHttpRequest
  var username = $("input#username").val();
  var password = $("input#password").val();

  var xhr = new XMLHttpRequest;

  xhr.open("GET", "login.php", true, username, senha);
  xhr.withCredentials = true;
  xhr.onreadystatechange = function () {
     if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
               console.log('resposta', xhr.responseText);
          } else {
               console.log('erro http', xhr.status);
          }
     }
  };
  xhr.send(null);
}

Auth Basic with jQuery.ajax

Your jQuery is all confusing, it does not need to:

async: false,

Neither:

data: '{"username": "' + username + '", "password" : "' + password + '"}',

And your btoa also has a function with parameters:

        xhr.setRequestHeader ("Authorization", "Basic " + btoa(function (user, password) {

What probably will not understand the scope of:

  var username = $("input#username").val();
  var password = $("input#password").val();

The correct one would be this:

function auth()
{
  //As variaveis devem vir dentro da função para poder pegar os valores só no momento que executar auth
  var username = $("#username").val();
  var password = $("#password").val();

  $.ajax({
     type: "GET",
     url: "login.php",
     dataType: 'json',
     beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
     },
     success: function (response){
        console.log(response);
     },
     error: function (response){
        console.log(response);
     }
  });
}
    
28.08.2018 / 16:06