Google Cloud Storage: Resumable Downloads with Service Accounts throws HTTP 401

666 views Asked by At

I'm trying to initialize a Resumable Download to Google Cloud Storage using a Service Account. The generated Authorization token is valid (I have verified it at https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=) and the Application has Full Control. However when I try to get a new URI for a resumable download I get a 401 Error (Invalid Credentials). What am I doing wrong here?

 40 $key = file_get_contents(KEY_FILE);
 41 $client->setAssertionCredentials(new Google_AssertionCredentials(
 42     SERVICE_ACCOUNT_NAME,
 43     array('https://www.googleapis.com/auth/devstorage.full_control'),
 44     $key)
 45 );
 46 
 47 $client->setClientId(CLIENT_ID);
 48 $service = new Google_StorageService($client);
 49 $buckets = $service->buckets;
 50 $bucketObj = new Google_Bucket();
 51 
 52 $time = time();
 53 $b_name = "test_bucket_"."$time";
 54 $bucketObj->setName($b_name);
 55 // $response = $buckets->insert('test_project-0001',$bucketObj);
 56 $response = $buckets->listBuckets('test_project-0001');
 57 $tokenStr = $client->getAccessToken();
 58 print "Token String : $tokenStr\n";
 59 $token = '';
 60 if(preg_match('/access_token\":\"(.*.)\",/', $tokenStr, $matches)) {
 61     print "Tken $matches[1] \n";
 62     $token = $matches[1];
 63 }
 64 
 65 
 66 $req = new Google_HttpRequest("https://www.googleapis.com/upload/storage/v1beta2/b/test_project-0001_test_bucket_1/o?uploadType=resumable&name=song");
 67 $req->setRequestHeaders(array(
 68                         'Authorization:' => "$token",
 69                         'X-Upload-Content-Length:' => '4509237'));
 74 $req->setRequestMethod('POST');
 75 // $req->setPostBody($e_body);
 76 
 77 var_dump($req);
 78 $gRest = new Google_REST();
 79 $response = $gRest->execute($req);
 80 var_dump($response);
 81 
 82 ?>

This gives me the following output { "error": { "errors": [{ "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" }], "code": 401, "message": "Invalid Credentials" } }

Could anyone give me some pointers on what I'm doing wrong?

1

There are 1 answers

0
Aditya On

I figured it out. Turns out I need to send an authenticated request like this:

63 $req->setRequestHeaders(array(
65                         'X-Upload-Content-Length:' => '4509237'));

(notice there's no Authentication parameter in the array)

77 $gcIO = new Google_CurlIO();
78 $response = $gcIO->authenticatedRequest($req);
79 $resp_uri = $response->getResponseHeader('location');

And that's that