如何使用cURL连接到Google Drive API?

时间:2018-07-17 05:00:24

标签: curl google-drive-api google-oauth

假设有三个步骤,

  1. 获取设备代码,
  2. 获取身份验证令牌
  3. 连接到Google云端硬盘。

步骤1: 当(且仅当)我忽略各种操作链接上列出的必要的redirect_url参数时,我才能通过步骤1。所以...

curl -d 'client_id=*client_id*' -d 'scope=https://www.googleapis.com/auth/drive.file' -d 'response_type=code' 'https://accounts.google.com/o/oauth2/device/code'

那时候的回报是...     {"device_code": "[device_code]", "user_code": "[user_code]", "expires_in": 1800, "interval": 5, "verification_url": "https://www.google.com/device"}

到目前为止很好。

步骤2: 这就是我卡住的地方。尝试了以下各种迭代:

curl -H 'Content-Type: application/x-www-form-urlencoded' -d 'client_id=**client_id**' -d 'client_secret=*client_secret*' -d 'grant_type=authorization_code' -d 'redirect_uri=urn:ietf:wg:oauth:2.0:oob' -d 'code=[device_code_from_above]' 'https://accounts.google.com/o/oauth2/token'

以上返回

{"error" : "invalid_grant", "error_description" : "Malformed auth code."}

如果将grant_type更改为'http://oauth.net/grant_type/device/1.0',则响应为

{"error" : "invalid_request", "error_description" : "Parameter not allowed for this message type: redirect_uri"}

如果redirect_uri被删除,则响应为

{"error" : "authorization_pending"}

上面的cURL尝试通过引用以下链接而拼凑而成... https://developers.google.com/identity/protocols/OAuth2ForDevices

http://www.visualab.org/index.php/using-google-rest-api-for-analytics#comment-157284

list google drive files with curl

Google Drive not listing files in folder

Not able to fetch Google OAuth 2.0 access token

https://www.daimto.com/google-authentication-with-curl/

S!

**编辑** 根据请求,这里的目标是:开发一种在文件上传时受到警报的方法,并拥有一个可以根据各种查询有选择地系统地下载文件的系统。

我们之所以没有使用Google云端硬盘的网络用户界面,原因是:文件大小很大:每个文件10-50GB,Google无法在不先压缩的情况下批量下载,也无法压缩任何大小以上的内容比我们最小的文件小。

我们之所以没有使用Google云端硬盘的APP的原因:无法(AFAIK)管理哪些文件可以在本地下载和不可以在本地下载,并且也无法(再次是AFAIK)存储到外部卷。 / p>

此外,我们正在将工作流程数据库集成到媒体上载和下载中:跟踪,日期,进度说明,版本等,这些都不是任何现有Google系统的一部分。因此,这里的目标是查看Google API对于所有这些可能具有的选项。

2 个答案:

答案 0 :(得分:4)

第一步获取代码

https://accounts.google.com/o/oauth2/auth?client_id=[Application Client Id]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=[Scopes]&response_type=code

将其放入浏览器窗口。并将代码复制到第二步。我怀疑问题出在您从第一步返回的代码中

第二步交换代码

您所链接的我的博客文章中使用的代码有一个要点链接。

如您所见,帖子数据应作为一个长查询字符串发送,并用&

分隔
  

-data'client_id = [应用程序客户端ID]&client_secret = [应用程序客户端密码]&refresh_token = [第二步授予的刷新令牌]&grant_type = refresh_token'\

googleauthenticationcurl.sh翻录的代码

# Client id from Google Developer console
# Client Secret from Google Developer console
# Scope this is a space seprated list of the scopes of access you are requesting.

# Authorization link.  Place this in a browser and copy the code that is returned after you accept the scopes.
https://accounts.google.com/o/oauth2/auth?client_id=[Application Client Id]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=[Scopes]&response_type=code

# Exchange Authorization code for an access token and a refresh token.

curl \
--request POST \
--data "code=[Authentcation code from authorization link]&client_id=[Application Client Id]&client_secret=[Application Client Secret]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code" \
https://accounts.google.com/o/oauth2/token

# Exchange a refresh token for a new access token.
curl \
--request POST \
--data 'client_id=[Application Client Id]&client_secret=[Application Client Secret]&refresh_token=[Refresh token granted by second step]&grant_type=refresh_token' \
https://accounts.google.com/o/oauth2/token

-d不带(')的

这似乎工作正常。我删除了不需要的标头,并且删除了代码中所有的('),我没有任何问题需要返回刷新令牌

curl -d client_id=103456123799103-vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.com -d client_secret=uxpj6hx1H2N5BFqdnaNhIbie -d grant_type=authorization_code -d redirect_uri=urn:ietf:wg:oauth:2.0:oob -d code=4/AABvK4EPc__nckJBK9UGFIhhls_69SBAyidj8J_o3Zz5-VJN6nz54ew https://accounts.google.com/o/oauth2/token

响应:

{
  "access_token" : "pO4LBSreV_r2i8kPklXVTqylXbMXip4OmQ0ZgRW0qZ8_b1ZP_zPJv0Xc_Qqsj9nM5ryWb7C81dYNFkO_bC6ifWA68dIlz40a0owG4GWpbZ2ufkHNXgre4",
  "expires_in" : 3600,
  "refresh_token" : "1/mEADfx6ffWULNBNFrKnlqOlK1uGL8Z546qBCHg",
  "token_type" : "Bearer"
}

答案 1 :(得分:0)

答案:

该问题的部分答案-'partial',因为它不使用纯cURL-但是可以使用PHP使其准备一些动态和SSL值,然后从PHP中运行cURL来使其工作

以下内容的关键参考来自Google的文档: https://developers.google.com/identity/protocols/OAuth2ServiceAccount

echo GoogleTokenRequest();

function GoogleTokenRequest(){
    $GoogleApiKeyInfo=GoogleApiKeyInfo();
    $Header=array();
    $Header["alg"]="RS256";
    $Header["typ"]="JWT";
    $ClaimSet=array();
    $ClaimSet["iss"]=$GoogleApiKeyInfo["client_email"];
    $ClaimSet["scope"]="https://www.googleapis.com/auth/drive";
    $ClaimSet["aud"]="https://www.googleapis.com/oauth2/v4/token";
    $ClaimSet["iat"]=time();
    $ClaimSet["exp"]=$ClaimSet["iat"]+(60);
    $Jws=base64_encode(json_encode($Header)).".".base64_encode(json_encode($ClaimSet));
    $OpenSslRslts=openssl_sign($Jws,$Signature,$GoogleApiKeyInfo["private_key"],OPENSSL_ALGO_SHA256);//Ref: http://php.net/manual/en/function.openssl-sign.php
    $Jwt=$Jws.".".base64_encode($Signature);
    $SendVars=array();
    $SendVars["grant_type"]=("urn:ietf:params:oauth:grant-type:jwt-bearer");
    $SendVars["assertion"]=$Jwt;
    $SendVars=http_build_query($SendVars);
    $UrlDomain="www.googleapis.com";
    $UrlPath="/oauth2/v4/token";
    $UrlFull=$UrlDomain.$UrlPath;
    $CurlType="Post";
    $ThisHeader=[
        strtoupper($CurlType)." ".$UrlPath,
        "Host: ".$UrlDomain,
        "Content-Type: application/x-www-form-urlencoded"
    ];
    return Process_cURL("https://".$UrlFull,$CurlType,$ThisHeader,$SendVars);
}

function GoogleApiKeyInfo(){
    //The following JSON data is downloaded from https://console.developers.google.com/apis/credentials when creating a project API key.
    return json_decode('{
    "type": "service_account",
    "project_id": "XXX",
    "private_key_id": "XXXX",
    "private_key": "-----BEGIN PRIVATE KEY-----VeryLongMultiLineString-----END PRIVATE KEY-----\n",
    "client_email": "xxxx@xxxx.iam.gserviceaccount.com",
    "client_id": "XXXXX",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxx@xxxx.iam.gserviceaccount.com"
    }');
}

function Process_cURL($ThisUrl,$ThisType,$ThisHeader,$ThisData){
    //Handler for a variety of cURL calls. Returns JSON string
}