I'm using Brent Shaffer's OAuth2 for PHP (https://github.com/bshaffer/oauth2-server-php)
I call my internal APIs like this:
$data = $fc->callAPI($_SERVER['HTTP_HOST'] . '/api/v1/test-member-search.php',
$fc->internalAccessTokenForAPI(), null);
callAPI
takes url, token, data and as you can see, I have a method for getting my own token. callAPI
is really just a cURL wrapper:
public function callAPI($fullURL, $token, $data ) {
$headers = [
'Accept: */*',
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Bearer ' . $token
];
if (!$data) { $data = ["data" => "none"]; }
// open connection
$ch = curl_init();
// set curl options
$options = [
CURLOPT_URL => $fullURL,
CURLOPT_POST => count($data),
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
];
curl_setopt_array($ch, $options);
// execute
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
The OAuth2 server can take the Authorization header or if not good, it checks for access_token
in the POST.
So that's how I access the API with PHP but what about an AJAX call like below:
<script type="text/javascript">
$(document).ready(function() {
var request;
$("#searchform").submit(function (event) {
event.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "/api/v1/test-member-search.php",
type: "post",
data: serializedData
});
...
... other stuff
This is where my knowledge ends. I can "make it work" by simply using PHP to echo the token from the PHP session as a hidden input called access_token
, or I could include it in the AJAX request data, but this makes the access token (which has a 1 hour life) visible to the browser client.
Knowing the access token gives the ability to make API calls so how do I call the API via AJAX and keep the token hidden?