2017-10-16 185 views
2

我正在尝试为服务器设置一个Google应用脚本API可执行文件,以便为我设置的Python微服务提供服务器身份验证。服务器到服务器Auth使用Google Apps脚本API可执行

使用快速入门,我能够通过Auth2使其工作,但我无法使它与服务帐户一起工作。我允许访问脚本和电子表格以服务帐户电子邮件。客户端密钥JSON中的项目ID与应用程序脚本的项目ID匹配。我将它作为一个API可执行文件进行部署。

这是我下面的代码(虽然我不认为代码是问题):

from oauth2client.service_account import ServiceAccountCredentials 
from httplib2 import Http 
from googleapiclient.discovery import build 


scopes = [ 
    'https://www.googleapis.com/auth/drive', 
    'https://www.googleapis.com/auth/script.external_request', 
    'https://www.googleapis.com/auth/script.storage', 
    'https://www.googleapis.com/auth/spreadsheets', 
    'https://www.googleapis.com/auth/userinfo.email' 
] 
credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scopes) 
http_auth = credentials.authorize(Http()) 
service = build('script', 'v1', http=http_auth) 


request = {'function': 'testApi'} 
response = service.scripts().run(body=request, scriptId='SCRIPT_ID').execute() 

print(response) 

的testApi功能在我的应用程序的脚本是一个简单的函数,返回“它的工作原理”。

我一直得知用户在使用个人帐户时没有权限(403),使用组织时(G Suite帐户)没有权限(403)。

如前所述,Google文档中的Quickstart教程正常工作,但未使用服务帐户。

是否有人将Google Apps脚本API可执行文件与服务器配合使用以使用服务器验证帐户流?

+0

您的服务帐户是否在管理控制台中拥有API客户端访问权限? (安全性>高级设置>管理API客户端访问)如果不是,则需要添加项目的服务帐户凭据并授予其访问适当的范围。 –

回答

1

您可能想查看本教程约Using Google Service Accounts with Google Apps Script。此示例代码展示了如何使用Service Accounts在Google Apps脚本中使用OAuth。

对于此代码工作,你需要create a Google Service accountdomain-wide delegation,替代私钥和客户端的电子邮件与实际值,也是客户端ID添加到与驱动器API范围的谷歌Apps管理员控制台。 OAuth 2.0访问令牌存储在脚本属性中。

var JSON = { 
    "private_key": "Your Private Key", 
    "client_email": "[email protected]", 
    "client_id": "1234567890", 
    "user_email": "[email protected]" 
}; 

function getOAuthService(user) { 
    return OAuth2.createService("Service Account") 
     .setTokenUrl('https://accounts.google.com/o/oauth2/token') 
     .setPrivateKey(JSON.private_key) 
     .setIssuer(JSON.client_email) 
     .setSubject(JSON.user_email) 
     .setPropertyStore(PropertiesService.getScriptProperties()) 
     .setParam('access_type', 'offline') 
     .setScope('https://www.googleapis.com/auth/drive'); 
} 

function getUserFiles() { 
    var service = getOAuthService(); 
    service.reset(); 
    if (service.hasAccess()) { 
     var url = 'https://www.googleapis.com/drive/v2/files?pageSize=1'; 
     var response = UrlFetchApp.fetch(url, { 
      headers: { 
       Authorization: 'Bearer ' + service.getAccessToken() 
      } 
     }); 
     Logger.log(response.getContentText()); 
    } 
} 

function reset() { 
    var service = getOAuthService(); 
    service.reset(); 
} 

另外,如果你所得到的403没有足够的权限错误,因为应用程序请求访问未在谷歌Apps管理控制台授权API范围是可能的。 invalid_grant错误很可能是由于承载应用程序的服务器的日期和时间设置不正确。

相关问题