2011-12-21 171 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