2013-07-30 92 views
7

我在使用Google新的Admin SDK時遇到困難。特別是使用Oauth2的Directory API。 我覺得我快到了,但是我試圖使用Directory API檢索用戶詳細信息(我正在使用Google教育版域)。Google管理API使用Oauth2獲取服務帳戶(教育版) - 403錯誤

基本上我想要做的是編寫一個python腳本,根據他們的註冊狀態(由我們的AD管理)來提供或取消供應用戶。我有一個使用Oauth1的腳本,但想更新它以使用Oauth2。

這是根據我發現的一些例子的代碼片段。

f = file('test_key.p12', 'rb') 
key = f.read() 
f.close() 
credentials = SignedJwtAssertionCredentials(
    '[email protected]', 
    key, 
    scope= 'https://www.googleapis.com/auth/admin.directory.user') 
http = httplib2.Http() 
http = credentials.authorize(http) 
service = build(serviceName='admin', version='directory_v1', http=http) 

lists = service.users().get(userKey='[email protected]').execute(http=http) 
pprint.pprint(lists) 

這段代碼似乎連接正確,但是當我嘗試執行查詢時,出現403錯誤。

錯誤:https://www.googleapis.com/admin/directory/v1/users/[email protected]?alt=json返回 「無權訪問該資源/ API」>

我的第一個想法是因爲我沒有在管理員控制檯(Google API's console)上打開這個API,但我有。 (其實我打開了Admin SDK而不是Directory API,因爲沒有Directory API可以打開,看到它是Admin SDK的一部分,它可以工作?)。

是否有另一步我失蹤或有我在某個地方犯了一個愚蠢的錯誤?

+0

你知道了嗎?我想知道Directory API(也就是Admin SDK API)是否可以與服務帳戶和OAuth 2.0一起使用。 (我知道其他API可以)。我明白它可以使用OAuth 1.0,但我還沒有嘗試過。 –

+0

@EricWalker - 是的見下面的評論。 – Bruce

回答

6

布魯斯,

你八九不離十。使用

所以完整的代碼看起來有點像這樣:

# domain configuration settings 
    import domainconfig 

    f = file(domainconfig.KEY_FILE, "rb") # b reads file in binary mode; not strictly necessary, but safer to avoid strange Windows EOL characters: https://stackoverflow.com/questions/9644110/difference-between-parsing-a-text-file-in-r-and-rb-mode 
    key = f.read() 
    f.close() 

    credentials = SignedJwtAssertionCredentials(

     domainconfig.SERVICE_ACCOUNT_EMAIL, 
     key, 
     scope = domainconfig.SCOPE, 
     sub=domainconfig.SUB_ACCOUNT_EMAIL # 'sub' supercedes the deprecated 'prn' 

    ) 

    http = httplib2.Http() 
    http = credentials.authorize(http) 

    directoryservice = build("admin", "directory_v1", http=http) 

    users = directoryservice.users() 
    response = users.get(userKey='[email protected]').execute() 
+0

如果使用Ruby和Google的'Signet',那麼當前需要對庫進行一些修改來模擬具有委派角色的管理員或用戶;請參閱:https://github.com/google/signet/pull/33 –

0

這應該是幫助:https://developers.google.com/drive/delegation

當斷言你需要將它連接到將要改變用戶的憑據。從上面的鏈接,請注意本節:

credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key, 
scope='https://www.googleapis.com/auth/drive', sub=user_email) 
相關問題