I'm making a new PhoneGap application, in which, I like to use AJAX for making an authenticated request to my server. For example, I want to see a statement of a customer. And I'm thinking about how to do authentication and retrieving data.
Server: PHP, MYSQL, SLIM FRAMEWORK In that, I've an endpoint called info.php
App: AJAX REQUEST, made from data saved from localStorage
Server Scrypt:
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
$app = new \Slim\App;
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
$name = $args['name'];
$response->getBody()->write("Hello, $name");
return $response;
});
$app->post('/aggiungi/{name}/{sur}', function (Request $request, Response $response, array $args) {
$this->logger->addInfo("Ticket list");
$name = $args['name'];
$sur = $args['sur'];
$mo = $name + $sur;
$response->getBody()->write("Hello, ".$mo);
$headers = $request->getHeaders();
$username = $headers['PHP_AUTH_USER'][0];
$password = $headers['PHP_AUTH_PW'][0];
$user = '';
$pass = 'mypwd';
try {
$dbh = new PDO('mysql:host=localhost;dbname=myserver', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$uname = $username;
$stmt = $dbh->prepare("MYQUERY");
$stmt->execute(array(':uname'=>$uname));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
if(password_verify($password, $userRow['password'])){
// AUTHENTICATED GO ON;
$a = "yes"; } else {
$a = "no";
header("HTTP/1.1 401 Unauthorized");
exit;
}
} else {
header("HTTP/1.1 401 Unauthorized");
exit;
$a = "no";
}
return "other stuff";
});
This endpoint check if in the database exits the user and the password is right. This is how i make AJAX request
var username = localStorage.username;
var password = localStorage.password;
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
Then, I would know if it is secure and if you can give me an advice on how to work.