3

新しいGoogle連絡先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)
 {
      ....
 }

このコードはうまく機能しますが、本番環境では OAuth2 認証を使用する必要があると Google は述べています。でさまざまなパラメーターを試しますRequestSettingsが、他のバリアントでは 401 (アクセスが拒否されました) になります。私の質問は、他のアカウントの資格情報を使用せずに、インストールされたデスクトップ アプリケーションで Google API v3 を介して認証する正しい方法です。

4

1 に答える 1

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 だと思います...多分私は間違っています、誰が知っていますか

于 2012-03-14T00:04:38.700 に答える