2011-12-21 170 views
3

我嘗試使用新的谷歌聯繫人API。 我的任務很簡單 - 從靜態(我的個人)域帳戶中檢索聯繫人。 註冊我的API控制檯應用程序,並得到客戶端Id,ClientSecret 所以我試圖通過.NET驗證我的應用程序(谷歌SDK)谷歌聯繫API v3身份驗證

RequestSettings settings = new RequestSettings(appName,login,password); 
ContactsRequest cr = new ContactsRequest(settings); 
Feed<Contact> contacts = cr.GetContacts(); 
foreach (Contact entry in contacts.Entries) 
{ 
     .... 
} 

此代碼的工作很好,但谷歌表示,我們應該在生產中使用的OAuth2認證場景。 我在RequestSettings嘗試不同的參數,但在其他變體中我得到401(拒絕訪問)。 所以我的問題什麼是正確的方式來驗證通過谷歌API V3在安裝桌面應用程序沒有使用其他帳戶的憑據。

+0

...谷歌說,我們應該使用的OAuth2 這是寫你應該權威性你這行後要求 RequestSettings設置=新RequestSettings(應用程序名稱); //在這裏添加授權令牌 ContactsRequest cr = new ContactsRequest(設置); 但他們沒有關於如何做到這一點 我已經綁定找到解決方案 無論如何使用OAuth 2.0,你可以在這裏閱讀https://developers.google.com/accounts/docs/OAuth2Login – 2012-03-13 22:34:11

回答

0

在開始工作之前,您應該獲得身份驗證令牌。爲此,您應該創建用戶應該打開的鏈接,並且可以訪問您的應用。 比你應該使用後來的代碼巫婆請求令牌。 這種機制在https://developers.google.com/accounts/docs/OAuth2Login 一些描述是這樣的:

 private const string GetTokenUrl = "https://accounts.google.com/o/oauth2/token";  
     private new bool Auth(bool needUserCredentionals = true) 
     { 
      var dic = new Dictionary<string, string>(); 
      dic.Add("grant_type", "authorization_code"); 
      dic.Add("code", ResponseCode); 
      dic.Add("client_id", ApplicationId); 
      dic.Add("client_secret", ApplicationSecret); 
      dic.Add("redirect_uri", HttpUtility.UrlEncode(AppRedirectUrl)); 
      var str = String.Join("&", dic.Select(item => item.Key + "=" + item.Value).ToArray()); 
      var client = new WebClient(); 
      client.Headers.Add("Content-type", "application/x-www-form-urlencoded"); 
      string s; 
      try { s = client.UploadString(GetTokenUrl, str); } 
      catch (WebException) { return false; } 
      catch (Exception) { return false; } 
      AuthResponse response; 
      try { response = JsonConvert.DeserializeObject<AuthResponse>(s); } 
      catch (Exception) { return false; } 
      Token = response.access_token; 
      SessionTime = DateTime.Now.Ticks + response.expires_in; 
      if (needUserCredentionals) 
       if (!GetUserInfo()) return false; 
      return true; 
     } 

     public class AuthResponse 
     { 
      public string access_token { get; set; } 
      public string token_type { get; set; } 
      public long expires_in { get; set; } 
     } 

ResponseCode這是一個代碼,用戶之後,你應該抓住什麼從「訪問授權頁」 重定向但這種方法是API 2我猜...也許我錯了,誰知道

+0

對不起AuthResponse是一個公共類AuthResponse { public string access_token {get;組; } public string token_type {get;組; } public string expires_in {get;組; } } – 2012-03-14 00:05:34

+0

和JsonConvert.DeserializeObject它是Newtonsoft.Json DLL的一部分,你可以從代碼plex – 2012-03-14 00:06:51

+0

得到它什麼是'GetTokenUrl'和'_gApi.Token'? – Alexei 2012-04-24 12:39:49