Friday, November 7, 2014

Basic http server authentication from mobile app via ajax

1. script for ajax 
function make_base_auth(user, password) {
  var tok = user + ':' + password;
  var hash = btoa(tok);
  return "Basic " + hash;
}
$.ajax({
type: 'POST',
beforeSend: function (xhr){  xhr.setRequestHeader('Authorization', make_base_auth("guest", "guest"));   },
xhrFields: {
withCredentials: true
}
,  crossDomain: true,
url: 'http://www.gtatrade.ca/mobiletest',
data: ({name: "aaa"}),
success: function(data){alert(data.name);},
error: function(e, x, settings, exception){alert("error!!" + "," + e.staus + ","  + e.responseText + ","  + x + ","  + settings + ","  + exception);},
dataType: 'json'
});

*** If you send header every time, use ajaxSetup like below.
$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', make_base_auth("guest", "guest"));
    }
xhrFields: {
withCredentials: true
}
,  crossDomain: true,
});

2. Server php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header("Access-Control-Allow-Origin: *"); // required for cross domain .. 
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization");
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
header("Access-Control-Allow-Origin: *");  // required for cross domain ..
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization");
    $output = array("name"=>$_SERVER['PHP_AUTH_USER'], "pass"=>$_SERVER['PHP_AUTH_PW']);
    echo json_encode($output);
}

No comments:

Post a Comment