首页 > 解决方案 > Google Drive API 在上传文件时返回 403

问题描述

这是登录后将文件上传到 Google 潜水的代码。

var accessToken = this.userData.token; // Here gapi is used for retrieving the access token.
console.log("accessToken :: " + accessToken);
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'}));
form.append('file', file);

var xhr = new XMLHttpRequest();
xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id');
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
console.log("XHR :: " + Object.values(xhr));
xhr.onload = () => {
    console.log(xhr.response.id); // Retrieve uploaded file ID.
};
xhr.send(file);
console.log("success.");

如果我使用用于生成 client_id 和 app_key 的帐户,它可以发布文件数据,但如果我使用任何其他帐户,则会出现如下错误。

https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id 403

我用相同的细节检查了 oAuth plaground 并得到了这样的响应。

Www-authenticate: Bearer realm="https://accounts.google.com/", error=insufficient_scope, scope="https://www.googleapis.com/auth/drive"
{
  "error": {
    "code": 403, 
    "message": "Insufficient Permission", 
    "errors": [
      {
        "domain": "global", 
        "message": "Insufficient Permission", 
        "reason": "insufficientPermissions"
      }
    ]
  }
}

标签: javascriptangularoauthgoogle-drive-apigoogle-oauth

解决方案


{
  "error": {
    "code": 403, 
    "message": "Insufficient Permission", 
    "errors": [
      {
        "domain": "global", 
        "message": "Insufficient Permission", 
        "reason": "insufficientPermissions"
      }
    ]
  }
}

与客户端 ID 无关。当用户运行您的应用程序时,系统会提示他们登录 google 并同意您的应用程序访问他们的 Google 驱动器帐户。您将获得一个 accessToken,授予您访问其驱动器帐户的权限。

Insufficient Permission意味着您拥有的 accessToken 无权执行您正在尝试执行的操作。我会检查您尝试上传此文件的位置。

  • 检查以确保您上传的是当前经过身份验证的用户驱动器帐户,而不是第一个用户的驱动器帐户?

  • 我看不到您如何验证用户身份,请确保您正在请求写入范围之一,也可能是您请求了错误的范围。


推荐阅读