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...
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:
– Reculos Gerbi Neto
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?
– Reculos Gerbi Neto
@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
– Guilherme Nascimento
Ok... I’ll check and get back to you as soon as possible! Thanks!
– Reculos Gerbi Neto
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...
– Reculos Gerbi Neto
@Reculosgerbinet which script you used, in jQuery or pure Xmlhttprequest?
– Guilherme Nascimento
Pure Xmlhttprequest
– Reculos Gerbi Neto