简体   繁体   中英

How do I authenticate against the Vebra feed using php?

Has anyone worked with the Vebra API? In their documentation they have a C# example for authentication but I'll be using php. They specify HTTP Basic Authentication with a username:password pair encoded to base 64.

The initial call requires the username:password pair and the result is a token. Subsequent calls require this token within a given timeframe (one hour).

I'm having problems using curl to authenticate let alone determine the token in the response header I need.

Have I used the correct options?

This is a basic curl effort I've written...

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

$result = curl_exec($ch);

// Handle the result - fail or success
if (!curl_errno($ch)) {

// get the response headers
//$info = curl_getinfo($ch);

var_dump ($result);
var_dump (curl_getinfo($ch));

// extract the token from the response header
//....
}
curl_close($ch);
?>

I've been struggling with this this morning, but think I've cracked it. So I'll summarise my code here:

// get token
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$userpass = "$username:$password";
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic '.base64_encode($userpass) )); // I found this to be the only way of consistently authorising between user-password combo and using a token

$response = curl_exec($ch);

// little bit of nasty parsing code    
list($headers, $body) = explode("\r\n\r\n", $response);
$headers = nl2br($headers);
$headers = explode('<br />', $headers);

foreach($headers as $header) {
    $components = explode(': ', trim($header));
    $headers[$components[0]] = $components[1];
}

$token = $headers['Token'];

and then subsequent calls need to use the the token, like so:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic '.base64_encode($token) ));

I've been using curl_getinfo() to check for a 401 status code and refreshing the token.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM