授权Google Apps脚本访问云端硬盘文件

时间:2014-03-06 00:16:16

标签: google-apps-script google-api google-drive-api google-oauth

以下代码适用于获取我自己的Google+用户属性:

// Google oAuth
function getAuth(service, scopes) {
   var oAuthConfig = UrlFetchApp.addOAuthService(service);
   oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken? scope="+scopes);
   oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
   oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
   oAuthConfig.setConsumerKey("anonymous");
   oAuthConfig.setConsumerSecret("anonymous");
   return {oAuthServiceName:service, oAuthUseToken:"always"};
 }

 function test_API_Key() {
    var gPlusAuth = getAuth("plus", "https://www.googleapis.com/auth/plus.me");
    var url = "https://www.googleapis.com/plus/v1/people/me?key=" + API_KEY;
    var httpResponse = UrlFetchApp.fetch(url, gPlusAuth);
    Logger.log(httpResponse);
  }

当我使用相同的方法访问我的Google云端硬盘上的文件元数据时,我遇到了HTTP错误403,并且“访问未配置”。下面是代码。我做错了什么?

function getFileMetaData(fileId) {
  var driveAuth = getAuth("drive", "https://www.googleapis.com/auth/drive");
  var url = "https://www.googleapis.com/drive/v2/files/" + 
        documentID + "?key=" + API_KEY;
  var response = UrlFetchApp.fetch(url, driveAuth);
  Logger.log(response);
}

1 个答案:

答案 0 :(得分:-1)

取自谷歌开发者网站[1]

在高级别,所有应用都遵循相同的基本授权模式:

  • 在Google Developers Console中注册该应用程序。
  • 请求用户授予对其Google帐户中数据的访问权限。
  • 如果用户同意,您的应用程序会请求并接收凭据以访问Drive API。
  • 刷新凭据(如有必要)。
  <script type="text/javascript">
    var CLIENT_ID = '<YOUR_CLIENT_ID>';
    var SCOPES = [
      'https://www.googleapis.com/auth/drive.file',
      'https://www.googleapis.com/auth/userinfo.email',
      'https://www.googleapis.com/auth/userinfo.profile',
      // Add other scopes needed by your application.
    ];

[1] https://developers.google.com/drive/web/about-auth

相关问题