-
Notifications
You must be signed in to change notification settings - Fork 41
PHP script to curl the endpoint
abidibo edited this page Sep 19, 2016
·
4 revisions
Given the following signature authentication class:
class MyAPISignatureAuthentication(SignatureAuthentication):
# The HTTP header used to pass the consumer key ID.
# Defaults to 'X-Api-Key'.
API_KEY_HEADER = 'X-Api-Key'
# A method to fetch (User instance, user_secret_string) from the
# consumer key ID, or None in case it is not found.
def fetch_user_data(self, api_key):
# custom stuff to retrieve user and secret key
try:
client = Client.objects.get(id_key=api_key)
return (client.user, client.secret_key)
except Client.DoesNotExist:
return None
the following php script can perform a valid request:
<?php
define('API_KEY', 'MY_API_KEY');
define('SECRET_KEY', 'MY_SECRET_KEY');
$Sig = base64_encode(hash_hmac('sha256', 'date: "'.gmdate('D, d M Y H:i:s T').'"', SECRET_KEY, true));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://localhost:8000/api/v1/path/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Accept: application/json',
'Accept-Encoding: gzip, deflate',
'Cache-Control: no-cache',
'Content-Type: application/json; charset=utf-8',
'Host: localhost',
'Date: "'.gmdate('D, d M Y H:i:s T').'"',
'X-Api-Key: '.API_KEY,
'Authorization: Signature keyId="'.API_KEY.'",algorithm="hmac-sha256",headers="date",signature="'.$Sig.'"'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
curl_close ($ch);
print $server_output ;
?>
Notice this line:
$Sig = base64_encode(hash_hmac('sha256', 'date: "'.date('r').'"', SECRET_KEY, true));
where date is lower case!