.net - Google 联系人 API v3 身份验证

标签 .net authentication oauth-2.0 google-contacts-api

我尝试使用新的谷歌联系人 API。 我的任务很简单——从静态(我的个人)域帐户中检索联系人。 我在 API 控制台注册我的应用程序并获取 ClientId、ClientSecret 所以我尝试通过 .net(google SDK) 验证我的应用程序

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

此代码运行良好,但 Google 表示我们应该在生产场景中使用 OAuth2 身份验证。 我在 RequestSettings 尝试不同的参数,但在其他变体中我得到 401(访问被拒绝)。 所以我的问题是,在不使用其他帐户凭据的情况下,在已安装的 desctop 应用程序中通过 google API v3 进行身份验证的正确方法是什么。

最佳答案

在开始工作之前,您应该获得授权 token 。为此,您应该创建用户应打开的链接并访问您的应用程序。 比您应该使用稍后获得的代码女巫请求 token 。 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...也许我错了,谁知道呢

关于.net - Google 联系人 API v3 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8591889/

相关文章:

ios - 如何在用户已登录 Facebook 的设备上登录时跳过 Facebook 的权限页面

c# - ASP.NET Web 应用程序中的身份验证遇到问题

html - firefox 将密码填入用户名字段

c# - Task.WaitAll 在所有任务完成之前返回

.net - 如何将 StringFormat 添加到 DataTemplate 内的 Textblock?

c# - Roslyn 是 Visual Studio 2017 的默认编译器吗

vbscript - 如何使用经典 ASP 和严格 OAuth 2.0 获取 GoToWebinar 的访问 token

c# - 代码中的表格布局被认为是错误的原因是什么?

facebook - facebook 如何随时使用access_token?

android - 客户经理刷新 token (离线访问)