2014-03-25 74 views
6

我正試圖製作一個服務器應用程序,將用戶添加/刪除到我的域組。請注意,它不會與用戶進行任何交互,它是服務器到服務器的應用程序。如何使用JWT使用NodeJS客戶端庫訪問Google Directory(Admin SDK)?

我登記我在谷歌API控制檯應用程序,下載的鑰匙,並轉化它通過發出

openssl pkcs12 -in my_google_key.p12 -out my_google_key.pem -nocerts -nodes 

然後我去過的域管理,安全爲.pem - >高級設置 - >認證 - >管理OAuth客戶端訪問。我在授權API客戶端添加了一條記錄。我用我從服務帳戶在控制檯中得到了客戶ID和使用範圍:

https://www.googleapis.com/auth/admin.directory.group.

我安裝的NodeJS googleapis,使用

npm install googleapis 

這裏是我的代碼:

var googleapis = require('googleapis'); 

var SERVICE_ACCOUNT_EMAIL = 'My Service Account E-mail Address'; 
var SERVICE_ACCOUNT_KEY_FILE = 'my_google_key.pem'; // The .pem file is at the root of my application 

var jwt = new googleapis.auth.JWT(
    SERVICE_ACCOUNT_EMAIL, 
    SERVICE_ACCOUNT_KEY_FILE, 
    null, 
    ['https://www.googleapis.com/auth/admin.directory.group'] 
); 

var client; 

googleapis 
.discover('admin', 'directory_v1') 
.execute(function(err, data) { 
    client = data; 

    jwt.authorize(function(err, result) { 
     console.log(jwt); 
     client.admin.groups.list({ 
      "customer": "my_customer", // This is actually "my_customer" 
      "domain": "domain.com" // The domain name I administer 
     }) 
     .withAuthClient(jwt) 
     .execute(function(err, result) { 
      console.log(err); 
      console.log(result); 
     }); 
    }); 
}); 

運行這段代碼的結果是:

{ errors: 
    [ { domain: 'global', 
     reason: 'forbidden', 
     message: 'Not Authorized to access this resource/api' } ], 
    code: 403, 
    message: 'Not Authorized to access this resource/api' } 

我錯過了什麼?如何使用Admin SDK授權我的應用程序?

回答

7

1)確保您委派域廣泛的權力,以您的服務帳戶。

2)服務帳戶必須模擬有人訪問管理員SDK目錄API。 https://developers.google.com/admin-sdk/directory/v1/guides/delegation#delegate_domain-wide_authority_to_your_service_account

var jwt = new googleapis.auth.JWT(
    SERVICE_ACCOUNT_EMAIL, 
    SERVICE_ACCOUNT_KEY_FILE, 
    null, 
    ['https://www.googleapis.com/auth/admin.directory.group'], 
    [email protected] 
); 

的文檔的本節詳細解釋這兩種:

初始化時,它包含

相關問題