2013-10-29 103 views
1

我是Google Apps域的管理員,並且正在嘗試編寫一個程序來訪問域中用戶的聯繫人(請注意,我是不是試圖獲取共享聯繫人,但每個用戶的個人聯繫人,所以共享聯繫人API不會幫助)。使用Google Contacts API訪問Google Apps域中的其他用戶的聯繫人

最初我使用三腳認證的「推薦」方法(顯示一個網頁,用戶批准使用該標記)。這很好,除非我嘗試了除我自己以外的任何用戶,否則我會得到一個403禁止的錯誤。那麼我讀到這種情況下我想要兩腳認證,雖然它已被棄用。

嗯,我已經想出了這個代碼,但現在我得到了401 /未經授權的憑證。我不確定問題出在我的代碼或其他地方(我註冊應用程序的方式或其他地方),但我很難找到有用的文檔。

 public static Feed<Contact> MakeRequest(string userId, int numberToRetrieve = 9999) 
     { 
      var settings = new RequestSettings(Properties.Settings.Default.ApplicationName, 
      Properties.Settings.Default.ApiKey, Properties.Settings.Default.ConsumerSecret, 
      Properties.Settings.Default.GoogleUserName, Properties.Settings.Default.Domain); 
      var cRequest = new ContactsRequest(settings); 
      var query = new ContactsQuery(ContactsQuery.CreateContactsUri(userId)); 
      query.NumberToRetrieve = numberToRetrieve; 
      return cRequest.Get(query); 
     }

回答

0

OK,我終於想通了。我覺得這個可能是不是它應該工作的方式,我不得不挖掘ServiceAccountCredential的源代碼,但它的工作原理。我實際上已經分開了一點,但爲了清晰起見,這完全是。

我也從Google.Apis.Authentication切換到Google.Apis.Auth。

public static Feed<Contact> MakeRequest(string userId, int numberToRetrieve = 9999) 
    { 
     var serviceCredential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(ServiceEmail) 
     { 
      Scopes = new[] { @"https://www.google.com/m8/feeds/" }, 
      User = userId, 
     }.FromCertificate(Certificate)); 

     var reqAccessTokenInfo = serviceCredential.GetType() 
      .GetMethod("RequestAccessToken", BindingFlags.Instance | BindingFlags.NonPublic); 
     var task = (Task<bool>) reqAccessTokenInfo.Invoke(serviceCredential, parameters: new object[] {new CancellationToken()}); 
     task.Wait(); 

     var settings = new RequestSettings(Properties.Settings.Default.ApplicationName, serviceCredential.Token.AccessToken); 
     var cRequest = new ContactsRequest(settings); 
     var query = new ContactsQuery(ContactsQuery.CreateContactsUri(userId)) { NumberToRetrieve = numberToRetrieve }; 

     return cRequest.Get<Contact>(query); 
    } 
1

使用3段OAuth時,只有在用戶通過OAuth握手進行特定身份驗證時纔有效。如果您想代表所有用戶撥打電話,則需要使用OAuth 2.0的服務帳戶。

查看驅動器API代碼示例,它將爲您提供一些有關如何從OAuth 2.0和服務帳戶開始的想法。

https://developers.google.com/drive/service-accounts#use_service_accounts_as_application-owned_accounts

如果您使用OAuth 1.0,那麼你就需要使用特殊的參數xoauth_requestor_id。下面是關於它的更多信息:

https://developers.google.com/accounts/docs/OAuth#GoogleAppsOAuth

+0

實際上,按照本指南進行操作時遇到了問題。特別是,當我轉到註冊的應用程序並選擇我的應用程序(在雲控制檯中)時,沒有顯示有關證書或服務帳戶的信息。相反,我只看到一個名爲「OAuth 2.0客戶端ID」的部分。難道我做錯了什麼? – Casey

+0

我最終設法創建了一個(我認爲)與舊的控制檯,但我也看不到如何實際應用您的示例。這描述了創建DriveService並將其傳遞給OAuth2Authenticator 對象。那麼好吧,除了ContactService沒有這樣的構造函數。我如何實際提出任何請求? – Casey

相關問題