如何为GOOGLE CLOUD JSON API创建承载令牌

时间:2018-05-21 08:19:57

标签: google-cloud-storage bearer-token bucket

要将对象上传到Google云端存储分区,我需要一个身份验证令牌。我选择了JSON API方法将对象上传到存储桶。

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,  "https://www.googleapis.com/upload/storage/v1/b/Mybucket/o?uploadType=media");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "yourdata");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$headers = array();
$headers[] = "Authorization:Bearer <TOKEN>";
$headers[] = "x-goog-project-id: xxxxxxxxxxx";
$headers[] = "x-goog-user-project: xxxxxxxxxxx";
$headers[] = "Content-Length: 8";
$headers[] = "Content-Type: image/jpeg";
$headers[] = "x-goog-acl: public-read-write";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
?>
  1. 有没有办法上传没有这些类型的对象 验证或任何其他身份验证方法?
  2. 如何使用api / curl / php以编程方式生成此令牌(bearer)?

1 个答案:

答案 0 :(得分:0)

function getOAuthToken(){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    $headers = array();
    $headers[] = "Metadata-Flavor: Google";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
      //  echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);
    $result = json_decode($result,true);
    return $result['access_token'];
}

$ result [&#39; access_token&#39;]是不记名令牌。