2017-10-16 212 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錯誤很可能是由於承載應用程序的服務器的日期和時間設置不正確。

相關問題