Skip to content

PHP script to curl the endpoint

abidibo edited this page Sep 9, 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 here
        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

$Sig = base64_encode(hash_hmac('sha256', 'date: "Fri, 09 Sep 2016 15:39:05 GMT"', 'SECRET', true));

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://localhost:8000/api/v1/newsletter/subscriberslist/");
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: http://localhost:8000',
    'Date: "Fri, 09 Sep 2016 15:39:05 GMT"',
    '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: "Fri, 09 Sep 2016 15:39:05 GMT"', 'SECRET', true));

where date is lower case!

Clone this wiki locally