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 ...