HTTP Basic Authentication with AJAX and php

Asked

Viewed 1,701 times

1

I am 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>
        <form name="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 message on the console. I switched console.log to Alert, and nothing happens!

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

The login.php is working, because I tested by accessing directly in the browser and typing the data in the browser request.

I need to create this solution because I must 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 put a print_r($_SERVER) in login.php

no indices appeared ['PHP_AUTH_USER'] nor the ['PHP_AUTH_PW'] in the array printing...

now with Xmlhttprequest I’m getting Alert, with the array print...

1 answer

1


As far as I know setRequestHeader expects 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 executed the function yet username and password are passed as parameters, ie won’t take the values of:

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

The object XmlHttpRequest already has parameters to pass the value of the authorisation, thus it must be so:

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 confused, he doesn’t need :

async: false,

Nor of:

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

And yours btoa also has a function with parameters:

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

Which probably won’t understand the scope of:

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

This would be right:

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);
     }
  });
}
  • cool... thanks for the tips... I made the changes, I’m trying to make the authentication using Xmlhttprequest that I’ve used before... it’s returning the answer:

  • Thanks for the tips...I made the changes... I also removed Ubmit from input and put button... I’m trying to authenticate using Xmlhttprequest that I’ve used before... it’s returning the answer: console.log('reply', xhr.responseText); in this case only the string 'reply' appears and nothing else...in the console the status of the login.php General Header is 200 OK, however it does not receive the echo "ENTERED";' which was to be the correct responseText?

  • @Reculosgerbineto then possibly is some error in your PHP, but some header is preventing PHP from generating error 500 (which is the correct error), take a look in the PHP folder, there should be a log with the errors, see the last errors of the log

  • Ok... I’ll check and get back to you as soon as possible! Thanks!

  • Coorrigindo the errors in the code I am able to check the returns of login.php, in case, the indices PHP_AUTH_USER and PHP_AUTH_PW are not set... then enter if(! isset...

  • @Reculosgerbinet which script you used, in jQuery or pure Xmlhttprequest?

  • Pure Xmlhttprequest

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.