4

我是一名网络开发人员,我想从我的商业软件访问 Google API,我创建了一个 Drive 帐户,我想通过代码 (VB.NET) 创建一个文件夹和文件。我正在关注文档,创建了 JWT(Json Web 令牌),使用了服务帐户并获得了访问令牌。

现在我想访问 Google API。使用控制台应用程序,我创建了一些文件夹,并且可以通过代码获取已创建文件夹的列表。但我在我的 Google Drive 帐户中看不到这些文件夹。这怎么可能?

这是我发送到服务器以显示文件夹和文件列表的请求: https://www.googleapis.com/files/ {FILE_ID}?key={API_KEY}

我获得一个 JSON 字符串作为响应,其中包含与 FILE_ID 元素相关的信息。例如:

{ "kind":"drive#file", "id":"FILE_ID", "mimeType":"application/vnd.google-apps.folder"(如果是文件夹) / "FILE_MIMETYPE"(如果是文件) , "title":"FOLDER_NAME" / "FILE_NAME", ... }

这是我用来访问 Google API 的代码:(VB.NET)

...

Public Function browseFile(ByVal fId As String) As List (Of FileSourceElement)

  Dim webclient As New WebClient()
  webclient.Headers.Add("Authorization", " Bearer " & _accessToken)
  webclient.Headers.Add("X-JavaScript-User-Agent", "Google APIs Explorer")
  Dim res As String = webclient.DownloadString("https://www.googleapis.com/drive/v2/files?key=" & _apiKey).Trim()

  'res contains the JSON with the informations of the file/folder 
  ...

End Function

Public Sub createContainer(ByVal path As String)
  Dim webclient As New WebClient()
  webclient.Headers.Add("Authorization", " Bearer " & _accessToken)
  webclient.Headers.Add("X-JavaScript-User-Agent", "Google APIs Explorer")
  webclient.Headers.Add("Content-Type", "application/json")
  webclient.UploadString("https://www.googleapis.com/drive/v2/files", _ 
                     "POST", _ 
                     "{""title"":""daEliminare2"", ""parents"":[{""id"":""" & path & """}], ""mimeType"":""application/vnd.google-apps.folder""}")
End Sub

...

在我的 Google Drive 中,我没有手动创建文件夹,也没有手动上传文件,我只能通过代码完成所有操作。

正如我对您所说,我已经成功创建了一个文件夹,并且我成功打印了文件列表(通过代码),但是在我的 GDrive 中,由 UI 创建的元素没有出现。为什么?


我在服务帐户中读到过,为了获得访问令牌,它需要一个名为 Json Web Token (JWT) 的特殊 JSON 字符串,该字符串由标头、声明集和签名(base64 字符串)组成。字符串是:

{base64 格式的 JWT 标头}。{base64 格式的 JWT 声明集}。{base64 格式的 JWT 签名}

我的智威汤逊是:

标题

{
  "alg": "RS256",
  "typ": "JWT"
}

Claim set { "iss": "0123456789@developer.gserviceaccount.com", // 其中 '0123456789' 是 CLIENT_ID。“范围”:“https://www.googleapis.com/auth/drive”,“aud”:“https://accounts.google.com/o/oauth2/token”,“exp”:timeStamp + 3600, //其中 'timeStamp' 是自 1970-01-01T00:00:00 以来的秒数。“iat”:时间戳}

要编写签名,我已按照此页面中描述的程序进行操作:

https://developers.google.com/accounts/docs/OAuth2ServiceAccount#computingsignature

编写 JWT 后,我将其发送到服务器,并在此模式下得到一个 JSON 字符串作为响应:

{
  "access_token": "ACCESS_TOKEN", // (e.g.: 1/8xbJqaOZXS...)
  "type_token": "Bearer",
  "expire_in": 3600
}

当我获得访问令牌 (AT) 时,我使用它来访问 Google API;例如:如果我要显示所有文件和文件夹列表,我会发送一个具有如下标题的请求:

授权:Bearer AT X-JavaScript-User-Agent:Google APIs Explorer

网址:https ://www.googleapis.com/drive/v2/files?key= {MY_API_KEY}

但我强调,列表中有一些项目(使用 VB.NET 控制台应用程序),而我的 Google Drive 中没有。

所以我得到了访问令牌,但我没有成功访问 Google API。

PS:我需要在不使用任何浏览器的情况下访问 Google API。

第二部分:

我在服务帐户中读到过,为了获取访问令牌,它需要一个名为 Json Web 令牌 (JWT) 的特殊 JSON 字符串,该字符串由标头、声明集和签名(base64 字符串)组成。字符串是:

{base64 格式的 JWT 标头}。{base64 格式的 JWT 声明集}。{base64 格式的 JWT 签名}

我的智威汤逊是:

标题

{
  "alg": "RS256",
  "typ": "JWT"
}

Claim set { "iss": "0123456789@developer.gserviceaccount.com", // 其中 '0123456789' 是 CLIENT_ID。“范围”:“https://www.googleapis.com/auth/drive”,“aud”:“https://accounts.google.com/o/oauth2/token”,“exp”:timeStamp + 3600, //其中 'timeStamp' 是自 1970-01-01T00:00:00 以来的秒数。“iat”:时间戳}

要编写签名,我已按照此页面中描述的程序进行操作:

https://developers.google.com/accounts/docs/OAuth2ServiceAccount#computingsignature

编写 JWT 后,我将其发送到服务器,并在此模式下得到一个 JSON 字符串作为响应:

{
  "access_token": "ACCESS_TOKEN", // (e.g.: 1/8xbJqaOZXS...)
  "type_token": "Bearer",
  "expire_in": 3600
}

当我获得访问令牌 (AT) 时,我使用它来访问 Google API;例如:如果我要显示所有文件和文件夹列表,我会发送一个具有如下标题的请求:

授权:Bearer AT X-JavaScript-User-Agent:Google APIs Explorer

网址:https ://www.googleapis.com/drive/v2/files?key= {MY_API_KEY}

但我强调,列表中有一些项目(使用 VB.NET 控制台应用程序),而我的 Google Drive 中没有。

所以我得到了访问令牌,但我没有成功访问 Google API。

PS:我需要在不使用任何浏览器的情况下访问 Google API。

致以真诚的感谢和诚挚的问候

国会议员

4

4 回答 4

6

由于您使用的是服务帐户,所有文件夹和文件都将在此服务帐户的驱动器中创建,无法通过 Web UI 访问,并且将限制为默认配额。

要在用户的云端硬盘中添加内容,您需要通过常规 OAuth 2.0 流程来检索该用户的凭据。您可以在此页面上找到有关 OAuth 2.0 的更多信息:

于 2012-08-31T15:44:48.003 回答
2

如果您想在不使用 OAuth 2.0 的情况下查看用户帐户下的文件,则可以将服务帐户编辑权限授予用户帐户下的文件夹。

然后,在使用服务帐户上传文件时,请确保将父参考 ID 设置为使用该文件夹 ID

文件夹 ID 在地址栏中确定

希望这可以帮助。

于 2013-04-05T00:59:50.643 回答
0

不知道给定的解决方案。在添加文件之后,我通过添加文件权限做了不同的事情(NodeJS 代码。insertFile 在用户的经典文件上传之后调用):

insertPermission = function(fileId, value, type, role,authClient,cb) {
  var body = {
    'value': value,
    'type': type,
    'role': role
  };
  var request = drive.permissions.insert({
    'fileId': fileId,
    'resource': body,
    'auth': authClient
  }, function (err,response) {
    cb(err,response);
  });
}

exports.insertFile = function(file,customer,callback) {
    exports.authorize(function (err,authClient) {
        drive.files.insert({
          resource: {
            title: file.name,
            mimeType: file.mimeType,
            parents: [{id:customer.googleDriveFolder}]
          },
          media: {
            mimeType: file.mimeType,
            body: file.buffer
          },
          auth: authClient
        }, function(err, response) {
          debug('error:', err, 'inserted:', response.id);
          if (!err) {
            insertPermission(response.id,customer.email,"user","writer",authClient,function (err,resp){
              callback(null, resp);            
            });
          }
        });
    });
};

请注意,我正在使用 JWT 和私钥类型的身份验证,并带有一个服务帐户:

exports.authorize = function(callback) {
    if (_tokens && ((_tokens.expiry_date - (new Date()).getTime())>100 )) callback(null, _authClient);
    else {

    var scope = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.appdata', 'https://www.googleapis.com/auth/drive.apps.readonly',
'https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive.metadata',
'https://www.googleapis.com/auth/drive.metadata.readonly',
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/drive.scripts'];

    var authClient = new google.auth.JWT(
            '<myServiceAccountClientId - xxx@developer.gserviceaccount.com>',
            '<path to key>.pem',
            ''); //seems we could use an user to impersonate requests, i need to test that..
    authClient.authorize(function(err, tokens) {
        if (err) {
            callback(err);
            return;
        }
        callback(null,authClient);    
    });
    }
};
于 2015-06-16T17:08:01.150 回答
0

您可以查看使用 API 上传的文件。使用以下 URL 查看您的所有文件。

https://drive.google.com/folderview?id=XXX

其中 XXX= 使用 API 创建的文件夹 ID。调试代码以获取文件夹 ID,

但是要在上面的链接中工作,您必须在创建任何文件夹或文件后提供权限,如下所示:

 Permission newPermission = new Permission();
 newPermission.Value = "youremail@gmail.com";
 newPermission.Type = "anyone";
 newPermission.Role = "reader";
 _service.Permissions.Insert(newPermission, NewDirectory.Id).Execute();

查看 UI 的备用链接:https ://drive.google.com/drive/folders/XXX

于 2015-09-02T05:14:23.407 回答